[英]Java Thread concept / demo
我正在尝试编写一个使用线程的Java程序。 我希望能够运行3个线程在程序启动时,并让他们等待的“工作单”的ArrayList。 最初,剧场将没有工作指令。 因此线程应等待。 在将来的某个时候,工作指令将添加到ArrayList中,并且主线程必须通知线程有工作要做。
我希望能够通过扩展Thread(而不是实现Runnable)来做到这一点。
我认为主要的问题我已经是线程都不能正确地与工作订单ArrayList的同步。
我的代码如下所示:
public static void main(String[] args) {
AnotherRunnable anotherRunnable = new AnotherRunnable();
ArrayList<ATMRunnable> workOrders = new ArrayList<ATMRunnable>();
T1 t1 = new T1(anotherRunnable, workOrders);
T1 t2 = new T1(anotherRunnable, workOrders);
t1.start();
t2.start();
try{
Thread.sleep(2000);
}
catch(InterruptedException e){}
synchronized (workOrders){
System.out.println(t1.getState() + " - " + t1.getName());
System.out.println(t2.getState() + " - " + t2.getName());
System.out.println("notify");
workOrders.notify();
System.out.println(t1.getState() + " - " + t1.getName());
System.out.println(t2.getState() + " - " + t2.getName());
}
}
该AnotherRunnable类:
public class AnotherRunnable implements Runnable {
public void run()
{
System.out.println("AnotherRunnable");
}
}
和Tread类:
公共类T1扩展了线程{
AnotherRunnable anotherRunnable;
ArrayList<ATMRunnable> workOrders;
ATMThread(AnotherRunnable anotherRunnable, ArrayList<ATMRunnable> workOrders)
{
this.anotherRunnable = anotherRunnable;
this.workOrders = workOrders;
}
public void run()
{
System.out.println("Run Thread");
synchronized (workOrders){
try{
System.out.println("wait Thread");
workOrders.wait();
}
catch (InterruptedException e){}
}
}
}
这是程序的输出:
Run Thread
wait Thread
Run Thread
wait Thread
WAITING - Thread-1
WAITING - Thread-2
notify all
BLOCKED - Thread-1
WAITING - Thread-2
如您所见,在对workOrders对象进行通知的调用之后,第一个线程的状态更改为“已阻止”。 但是线程和可运行对象均未执行。
任何帮助将不胜感激。
您应该在Java中使用并发集合,以尽可能避免手动同步。
我希望能够运行3个线程在程序启动时,并让他们等待的“工作单”的ArrayList。 最初,剧场将没有工作指令。 因此线程应等待。 在将来的某个时候,工作指令将添加到ArrayList中,并且主线程必须通知线程有工作要做。
对于这种同步, 阻塞队列是您喜欢的LinkedBlockingQueue之类的朋友,当队列中没有任何项目或队列已满时,它们使线程等待。 您不需要在那里进行任何同步/等待/通知。
您还可以检查是否有帮助: 同步存在风险
如果仅出于学习目的,则必须首先在逻辑上使同步正确。 它不使用任何条件等待或通知问题。 如果合适,它将起作用,但不是首选方法。
我发现我需要做些什么才能使它工作。 主要是缺少该概念。 我不得不循环运行线程的方法。 我以为每次调用notifyall都会调用该方法,这是不正确的。 当在同步对象上调用wait()时,线程将停止,并通过通知它恢复执行,如果该代码不在循环中,则将不执行该线程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.