为什么主线程没有被抢占?

时间:2018-06-04 18:08:43

标签: java multithreading static singleton

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] ]  实际产量:  [MainThread]  [SingleTonThread]

1 个答案:

答案 0 :(得分:2)

致电:

sleep(1000)

您已通过调用

阻止了主线程
executeMethod("MainThread")

启动线程类的以下行将在

之前执行
files = $(basename $(shell ls *.c))
all: $(files)
%: %.c                                                             
    gcc $< -o $@                                                                

将完成执行

顺便说一句,在构造函数as described in this question

中启动一个线程是一种非常糟糕的做法