并非所有线程都用于调用方法



我正在使用线程构造函数来创建线程。我期望下面的代码由3个独立的线程和不同的输出执行。有人能解释一下为什么输出与我的理解不同吗(为什么线程2被用来调用m1两次而不是t3(?

代码:-

public static void main( String[] args ) {
new SynchronizedExample().execute();
}
void execute() {
SynchronizedExample s1 = new SynchronizedExample();
Thread t1 = new Thread(s1::m1);
Thread t2 = new Thread(s1::m1);
Thread t3 = new Thread(s1::m2);
t1.start();
t2.start();
t3.start();
}
public synchronized void m1(){
try {
System.out.println("Current Thread - " + Thread.currentThread().getName());
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("M1");
}
public void m2() {
System.out.println("M2");
}
}

输出:-

Current Thread - Thread-0
M2
M1
Current Thread - Thread-1
M1

预期输出:-

Current Thread - Thread-0
M2
Current Thread - Thread-1
M1
Current Thread - Thread-2
M1

您让它变得令人困惑。

我会注释你的输出:

Current Thread - Thread-0 [t1 - m1]
M2 [t3 - m2]
M1 [t1 - m1]
Current Thread - Thread-1 [t2 - m1]
M1 [t2 - m1]

您的代码打印一些东西,然后等待,然后打印更多。因此,单个方法会将其System.out行涂抹在第一行和第三行上。您的m2方法根本不打印Current Thread - ...,所以您所期望的显然不可能发生。添加打印。

最新更新