【问题标题】:Why Main thread is not getting preempted here?为什么主线程在这里没有被抢占?
【发布时间】:2018-06-04 18:08:42
【问题描述】:
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] ] 实际输出: [主线程] [SingleTonThread]

【问题讨论】:

  • 你在启动另一个线程之前就完成了executeMethod("Main Thread") - 睡眠和所有的执行。

标签: java multithreading static singleton


【解决方案1】:

调用时:

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

你已经通过调用阻塞了主线程

sleep(1000)

下面启动线程类的行直到

executeMethod("MainThread")

将完成执行

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-15
    • 2020-11-21
    • 2010-10-23
    • 1970-01-01
    • 2019-06-15
    • 2021-05-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多