上面的prog通过调用wait()和join()来工作。你能告诉我我应该用哪种方法吗?或者是否有更好的方法提前编写这个程序.Thanks :)对于thread.wait(),我在调用t.start()之前创建一个同步块。
public class DisplayThread {
public synchronized void printThread(int threadNumber){
System.out.println("I am thread number: " + threadNumber);
}
}
public class Thread1 extends Thread {
DisplayThread d;
int num;
Thread1(DisplayThread d, int num) {
this.d = d;
this.num = num;
}
public void run() {
d.printThread(num);
}
public static void main(String[] args) {
DisplayThread d = new DisplayThread();
Thread[] t = new Thread[10];
for (int i = 0; i < 10; i++) {
t[i] = new Thread1(d, i);
t[i].start();
try {
t[i].join(); **//t[i].wait(1000) also works fine**
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}发布于 2017-04-15 18:53:54
如果您的目标是同时执行10个Thread,则需要将Thread#join调用移到初始循环之外。
for (int i = 0; i < 10; i++) {
t[i] = new Thread1(d, i);
t[i].start();
}
for (int i = 0; i < 10; i++) {
try {
t[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}除此之外,在我看来一切都很好!
发布于 2017-04-15 18:51:09
你能告诉我该用哪种方法吗?
您只需要使用join()方法来告诉main线程不要启动迭代中的下一个线程(即行t[i].start())。如果不使用join(),main线程也会并行运行,并启动其他线程。
另外,wait()和notify()旨在解决另一个问题,即生产者/消费者问题,我建议您看看这里来了解这个概念是如何工作的。
https://stackoverflow.com/questions/43429892
复制相似问题