gpt4 book ai didi

java - 为什么主线程在这里没有被抢占?

转载 作者:行者123 更新时间:2023-11-30 02:08:48 25 4
gpt4 key购买 nike

public class SingletonClass {
private static SingletonClass singletonClass;
public void executeMethod(String string) {
System.out.print("["+string);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("]");
}
private SingletonClass() {

}
public static SingletonClass getInstance() {
if(singletonClass==null)
singletonClass=new SingletonClass();
return singletonClass;
}

public static void main(String args[]) {
SingletonClass.getInstance().executeMethod("MainThread");
new SingleTonThread(SingletonClass.getInstance());
}

}

class SingleTonThread implements Runnable{
private SingletonClass sc;
SingleTonThread(SingletonClass singleton){
this.sc=singleton;
Thread t = new Thread(this);
t.start();
}
@Override
public void run() {
sc.executeMethod("SingleTonThread");
}

}

我期望以下输出(因为主线程应该被 SingleTonThread 抢占):预期输出:[MainThread[SingleTonThread]] 实际输出: [主线] [单吨线程]

最佳答案

调用时:

SingletonClass.getInstance().executeMethod("MainThread");

您已通过调用阻塞了主线程

sleep(1000)

下面启动线程类的行将不会被执行,直到

executeMethod("MainThread")

即将执行完毕

顺便说一句,在构造函数中启动线程是一种非常糟糕的做法 as described in this question

关于java - 为什么主线程在这里没有被抢占?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50686424/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com