我的代码有问题。
我的任务是wrtie程序,它将类似于一些工厂生产煎饼,我必须使用同步队列。
有三个步骤:
1.油炸
之后在另一个线程中:
2.润滑
最后一个是:
3.卷起这个煎饼:(
在我的程序中,我开始油炸;放置";,这意味着我正在等待呼叫";取";在另一种方法中。但它不起作用。当程序想要调用";润滑";Greasing类中的方法。
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();
}
工厂类别:
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");
}
}
润滑等级:
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();
}
}
}
汇总类:
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();
}
}
}
您有两种问题:
-
从代码中删除
notify()
和sychronized
,这会阻止您,因为synchronized
会锁定Factory类,因此两个线程不能同时进入Factory同步方法。最好将代码移到正确的类中,Greasing必须发生在Greasing类中。这将帮助你制定秩序,并将其视为对象进行思考。 -
修复了1。您将看到,现在每个操作都会发生,直到所有线程都在
put
上等待。这是因为您需要为每个";消费者";。在您的代码中,您可以通过油炸触发Rollingup,因为列表中的对象之间没有区别。
Frying操作必须将对象放入润滑队列,润滑操作必须从其队列中消耗,然后将对象放入Rollingup队列