我有一个程序,其中我创建了10个线程来运行。我希望主线程等到所有事情完成之前完成。我试图使用.join命令,但它似乎并没有工作。此外,我试图显示所有线程的运行时间,但它无法正常工作。以下是我的代码。如何使主要等待所有线程完成
//File: CohanThread.java
//Author: Ryan A. Cohan
//Date: August 4, 2016
//Purpose: To create, run, and analyze a thread based program. IOBound runs IO intensive
//operations in the form of printing 1000 times to the console. CPUBound runs CPU
//intensive operations by computing an equation and printing 1000 times.
package cohanthread;
import java.text.*;
public class CohanThread{
public static void main(String args[]) throws InterruptedException{
NumberFormat formatter = new DecimalFormat("#0.00000");
IOBound io1 = new IOBound();
IOBound io2 = new IOBound();
IOBound io3 = new IOBound();
IOBound io4 = new IOBound();
IOBound io5 = new IOBound();
CPUBound cpu1 = new CPUBound();
CPUBound cpu2 = new CPUBound();
CPUBound cpu3 = new CPUBound();
CPUBound cpu4 = new CPUBound();
CPUBound cpu5 = new CPUBound();
long scheduleStart = System.currentTimeMillis();
io1.start();
io2.join();
io3.join();
io4.join();
io5.join();
cpu1.join();
cpu2.join();
cpu3.join();
cpu4.join();
cpu5.join();
long scheduleEnd = System.currentTimeMillis();
System.out.println("Runtime of all threads: " + formatter.format((scheduleEnd - scheduleStart)/1000d));
System.out.println("Processes complete.");
}
}
class IOBound extends Thread{
NumberFormat formatter = new DecimalFormat("#0.00000");
@Override
public void run(){
long start = System.currentTimeMillis();
for(int i = 0; i < 1000; i++){
System.out.println("Thread number is: " + i);
}
long end = System.currentTimeMillis();
System.out.println("IO Thread runtime: " + formatter.format((end - start)/1000d));
}
}
class CPUBound extends Thread{
NumberFormat formatter = new DecimalFormat("#0.00000");
@Override
public void run(){
String binary = "";
long start = System.currentTimeMillis();
for(int i = 0; i < 1000; i++){
while(i > 0){
int remainder = i % 2;
binary = remainder + binary;
i = i/2;
}
System.out.println("Binary number: " + binary);
long end = System.currentTimeMillis();
System.out.println("CPU Thread runtime: " + formatter.format((end - start)/1000d));
}
}
}
“它似乎没有工作”---'join()'按照指定的方式工作。 –
你正在加入未激活的主题?除此之外:“不起作用”不是一个足够的错误描述。请提供您期望的与您所观察到的相反的内容。 – Fildor
你开始一个线程,并加入除了你真正开始的线程之外的所有其他线程。 –