我有多個線程需要等待對方來完成一個進程。由於需求,必須這樣做。如果我顯示代碼並顯示預期的輸出,那麼這將是有意義的。這是我的主類:單步執行多個線程
public static ThreadedJob job1, job2;
public static ArrayList<Thread> threads = new ArrayList<Thread>();
public static void main(String[] rags) throws InterruptedException{
job1 = new Job1("Thread1:");
job2 = new Job2("Thread2:");
job1.run();
job2.run();
threads.add(new Thread(job1));
threads.add(new Thread(job2));
if (job1.getCounter() > job2.getCounter()) {
threads.get(0).wait();
threads.get(1).notify();
}
if (job1.getCounter() < job2.getCounter()) {
threads.get(1).wait();
System.out.println(true);
threads.get(0).notify();
}
}
這裏是螺紋作業類,(作業1和作業2類現在只是延長和調用super(名稱),這是所有)
public class ThreadedJob implements Runnable{
protected String name;
protected int counter = 0;
public ThreadedJob(String name){
this.name = name;
}
@Override
public void run() {
System.out.println(name + " job 1 complete");
counter++;
System.out.println(name + " job 2 complete");
counter++;
System.out.println(name + " job 3 complete");
counter++;
}
public int getCounter(){ return counter; }
}
這裏是預期輸出:
Thread1: job 1 complete Thread2: job 1 complete Thread1: job 2 complete Thread2: job 2 complete Thread1: job 3 complete Thread2: job 3 complete
這裏是從我的代碼輸出:
Thread1: job 1 complete Thread1: job 2 complete Thread1: job 3 complete Thread2: job 1 complete Thread2: job 2 complete Thread2: job 3 complete
問題:如何讓線程暫停,允許放開,然後繼續。非常多的是,我怎樣才能讓他們一步步地等待產生預期的產出。謝謝!
重要提示:這需要線程的X量的工作,我只是正與2同樣的測試,線程與不同的邏輯大部分是在實際應用時運行,但不允許在工作同一時間。
我想你忘了開始你的線程 - 你直接運行runnables。線程沒有做任何事情。無論如何,一旦你得到了排序,看看'CyclicBarrier'和'CountdownLatch'。 – RealSkeptic
@RealSkeptic我以爲我做了......除了run()之外,我該怎麼做? – Luke
啊。那麼,你需要從非常基本的線程開始。使用'run'方法在當前線程**中運行runnable **,並且不啓動線程。看看[Oracle教程](https://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html)。 – RealSkeptic