Nic*_*ner 16 java concurrency multithreading join
我是线程的新手.我怎样才能开始t.join
工作,调用它的线程会等到t执行完毕?
这段代码只会冻结程序,因为线程正在等待自己死掉,对吧?
public static void main(String[] args) throws InterruptedException {
Thread t0 = new Thready();
t0.start();
}
@Override
public void run() {
for (String s : info) {
try {
join();
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.printf("%s %s%n", getName(), s);
}
}
Run Code Online (Sandbox Code Playgroud)
如果我想要有两个线程,我会怎么做,其中一个线程打印出一半的info
数组,然后在完成剩下的工作之前等待另一个完成?
Fra*_* IV 17
使用这样的东西:
public void executeMultiThread(int numThreads)
throws Exception
{
List threads = new ArrayList();
for (int i = 0; i < numThreads; i++)
{
Thread t = new Thread(new Runnable()
{
public void run()
{
// do your work
}
});
// System.out.println("STARTING: " + t);
t.start();
threads.add(t);
}
for (int i = 0; i < threads.size(); i++)
{
// Big number to wait so this can be debugged
// System.out.println("JOINING: " + threads.get(i));
((Thread)threads.get(i)).join(1000000);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
51197 次 |
最近记录: |