I've got problem with my code.
My task is wrtie program, which will resemble some factory producing pancake and I have to use a synchronous queue.
There is three steps:
1. Frying.
After that in another thread:
2. Greasing.
And the last one is:
3. Rolling up this pancake:)
In my program I start frying and I create "put", which means I'm waiting for call "take" in another method. But it doesn't work. It stops when the program wants to call "greasing" method in Greasing class.
main:
public static void main(String[] args) {
Factory f1 = new Factory();
f1.start();
Greasing g1 = new Greasing(f1);
g1.start();
RollingUp r1 = new RollingUp(f1);
r1.start();
}
Factory Class:
public class Factory extends Thread{
// 0 - frying
// 1 - greasing
// 2 - rolling up
SynchronousQueue<String> list = new SynchronousQueue<>();
@Override
public void run() {
try{
while(true) frying();
}catch(InterruptedException e){
e.printStackTrace();
}
}
private synchronized void frying()throws InterruptedException{
System.out.println("I'm frying now");
list.put("Frying");
notify();
}
public synchronized void greasing() throws InterruptedException{
notify();
list.take();
System.out.println("I'm greasing now");
list.put("Greasing");
}
public synchronized void rollingup()throws InterruptedException{
notify();
list.take();
System.out.println("I'm rolling up now");
list.put("Rolling up");
}
}
Greasing class:
public class Greasing extends Thread{
Factory f1;
public Greasing(Factory f1) {
this.f1 = f1;
}
@Override
public void run() {
try{
while(true){
f1.greasing();
sleep(1000);
}
}catch(Exception e){
e.getMessage();
}
}
}
RollingUp class:
public class RollingUp extends Thread{
Factory f1;
RollingUp(Factory f1){
this.f1 = f1;
}
@Override
public void run() {
try{
while(true){
f1.rollingup();
sleep(1000);
}
}catch(Exception e){
e.getMessage();
}
}
}
CodePudding user response:
You have two kind of problems:
Remove
notify()
ansychronized
from your code, this is blocking you because thesynchronized
puts a lock on the Factory class, so 2 threads cannot enter the Factory sync methods in the same moment. Better to move the code in the right class, the Greasing must occur in the Greasing class. This will help you to make order and to think as objects.Fixed the 1. you will see that every operation now take place until when you have all the threads waiting on the
put
. This is because you need to have a different queue for every "consumer". In your code you can have a Rollingup triggered from the frying because there is no distinction between the objects in the list.
The Frying operation must put the object in the greasing queue, the Greasing operation must consume from his queue and then put an object in the Rollingup queue