我有一個main方法是這樣的:多線程Java中
A a = new A();
a.start();
B b = new B();
b.start();
B工作對a.start產生如此a.start(文件)必須完成first.However, a.start ()運行多線程作業,並在執行之前執行b.start()。
- 爲什麼啓動a.start()的主線程在完成之前退出該方法?
- 確保b.start()在a.start()完成之前不會啓動的好方法是什麼?
謝謝!
我有一個main方法是這樣的:多線程Java中
A a = new A();
a.start();
B b = new B();
b.start();
B工作對a.start產生如此a.start(文件)必須完成first.However, a.start ()運行多線程作業,並在執行之前執行b.start()。
謝謝!
看起來你並不需要在所有執行單獨的線程這些任務,但如果你真的想你可以做這樣的事情:
A a = new A();
a.start();
a.join(); // Will wait until thread A is done
B b = new B();
b.start();
b.join(); // Will wait until thread B is done
假設A和B是Thread類的子類,不鼓勵實現Runnable並使用新線程(Runnable).start()。
更好的方法是使用Executor並讓A和B實現Runnable(不擴展Thread)。像這樣:
ExecutorService ex = Executors.newSingleThreadExecutor();
ex.execute(new A());
ex.execute(new B());
A和B現在將在一個單獨的線程上按順序執行。
+1想要多次投票。 ;) – 2011-01-20 11:49:52
謝謝! 由於文本最小長度的原因,需要寫東西... – user431336 2011-01-21 08:38:19
不要直接使用線程,去上級java.util.concurrent庫
它來,因爲JVM決定執行哪個線程,你無法預測它。加入和併發utils是最好的方式,因爲它已經在下面指出。 – 2011-01-20 11:23:18