我有以下课程
class ThreadDemo extends Thread {
private Thread t;
private String threadName;
ThreadDemo( String name) {
threadName = name;
}
public void run() {
for(int i = 5; i > 0; i--) {
System.out.println("Thread " + threadName + " Counter --- " + i );
}
try {
Thread.sleep(1000);
} catch (Exception e) {
System.out.println("Sleep issue");
}
System.out.println("Finishing run");
try {
Thread.sleep(1000);
} catch (Exception e) {
System.out.println("Sleep issue");
}
}
public void start () {
t = new Thread (this, threadName);
t.start ();
}
}
如下所示进行测试
public class Main {
public static void main(String[] args) {
ThreadDemo T1 = new ThreadDemo( "Thread - 1 ");
ThreadDemo T2 = new ThreadDemo( "Thread - 2 ");
T1.start();
T2.start();
//Let's give some time for threads to run
try {
Thread.sleep(10);
} catch (Exception e) {
System.out.println("Main sleep issue");
}
try {
T1.join();
T2.join();
} catch ( Exception e) {
System.out.println("Interrupted");
}
System.out.println("Finishing main.");
}
}
为什么我总是得到"完成主要"之前"完成运行"尽管我使用T1.join()和T2.join()来等待它们完成,但在输出中?最初我认为这可能是由于缓冲延迟所以我在run()的末尾添加了Thread.sleep(1000)以给出一些时间来打印"完成运行"但它没有帮助。我猜它是由于第一次出现Thread.sleep(1000)(当我删除它时,它工作正常)但不知道为什么。
答案 0 :(得分:5)
因为这个原因:
public void start () {
t = new Thread (this, threadName);
t.start ();
}
因此,您的ThreadDemo
实例永远不会作为线程启动:打印Finishing run
消息的线程是在该方法中创建的线程。该线程与ThreadDemo
之间没有链接。
删除start()
方法。