为什么我不能得到正确的输出? 这是我的代码:
=======
1.主要内容
public class ThreadDebut {
public static void main(String args[]) {
PrintDemo PD = new PrintDemo();
List<ThreadDemo> th = new ArrayList<ThreadDemo>();
ThreadDemo T1 = new ThreadDemo( "Thread - 1 ", PD );
ThreadDemo T2 = new ThreadDemo( "Thread - 2 ", PD );
T1.start();
th.add(T1);
T2.start();
th.add(T2);
for(ThreadDemo t : th) {
try {
t.join();
}catch( Exception e) {
System.out.println("Interrupted");
}
}
System.out.println("\n\n\n");
}
}
2.线程和方法
class PrintDemo {
public void printCount() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Counter --- " + i );
}
}catch (Exception e) {
System.out.println("Thread interrupted.");
}
}
}
class ThreadDemo extends Thread {
private Thread t;
private String threadName;
PrintDemo PD;
ThreadDemo( String name, PrintDemo pd) {
threadName = name;
PD = pd;
}
public void run() {
synchronized(PD) {
PD.printCount();
}
System.out.println("Thread " + threadName + " exiting.");
}
public void start () {
System.out.println("Starting " + threadName );
if (t == null) {
t = new Thread (this, threadName);
t.start ();
}
}
}
我的意思是我想在两个线程执行完毕后得到这个System.out.println("\n\n\n");。但是,在线程 1 的同步之前,我得到的只是随机的。我已经执行了 thread.join() 但失败了。为什么?请有人向我解释一下...谢谢并问候!!!
最佳答案
您正在尝试同时子类化和使用委托(delegate)。您本质上为每个线程创建两个线程。您应该重写 Thread 的方法,而不是使用委托(delegate)。就像这样:
static class ThreadDemo extends Thread {
private String threadName;
PrintDemo PD;
ThreadDemo (String name, PrintDemo pd) {
threadName = name;
PD = pd;
}
@Override
public void run() {
synchronized (PD) {
PD.printCount();
}
System.out.println("Thread " + threadName + " exiting.");
}
@Override
public void start() {
System.out.println("Starting " + threadName);
}
}
关于java - 多线程后无法获得正确的执行时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41744283/