寻找 Thread.sleep() 方法的清晰度

问题描述 投票:0回答:1

Thread.sleep() 方法使运行它的线程进入睡眠状态。 下面代码中的 thread.sleep() 语句将由主线程运行,下面代码中的“thread”是用户定义的线程。为什么在用户定义线程的引用上调用时主线程正在休眠。

public class ThreadDemo {

    public static Thread t1 = null;
    public static Thread t2 = null;
    public static void main(String[] args) throws InterruptedException{

        System.out.println("start of main function, Thread : "+Thread.currentThread().getName());
        t1 = Thread.currentThread(); //main thread
        MyThread thread = new MyThread();
        t2 = thread;
        thread.start();

        System.out.println("Before sleep in main method : "+System.currentTimeMillis());
        thread.sleep(1000);
        System.out.println("After sleep in main method : "+System.currentTimeMillis());

        System.out.println("In main method, Thread : "+t1.getName()+" ,In state: "+t1.getState());
        System.out.println("In main method, Thread : "+t2.getName()+" ,In state: "+t2.getState());

        System.out.println("Is thread, "+thread.getName() + " alive : "+ thread.isAlive());

        System.out.println("end of main function, Thread : "+Thread.currentThread().getName());
    }

    public static class MyThread extends Thread{
        int sum = 0;
        @Override
        public void run() {
            System.out.println("In run method, Thread : "+t1.getName()+" ,In state: "+t1.getState());
            System.out.println("In run method, Thread : "+t2.getName()+" ,In state: "+t2.getState());
            System.out.println("start of run method, Thread : "+Thread.currentThread().getName());
            for(int i=0; i<10000; i++){
                sum += i;
            }
            try{
                Thread.sleep(10000);
                System.out.println("After sleep in run method : "+System.currentTimeMillis());
            }catch (InterruptedException e){
                e.printStackTrace();
            }
            System.out.println("end of run method, "+ Thread.currentThread().getName() +", returns : "+sum);
        }
    }
}

输出:

start of main function, Thread : main
Before sleep in main method : 1701105524066
In run method, Thread : main ,In state: TIMED_WAITING
In run method, Thread : Thread-0 ,In state: RUNNABLE
start of run method, Thread : Thread-0
After sleep in main method : 1701105525070
In main method, Thread : main ,In state: RUNNABLE
In main method, Thread : Thread-0 ,In state: TIMED_WAITING
Is thread, Thread-0 alive : true
end of main function, Thread : main
After sleep in run method : 1701105534071
end of run method, Thread-0, returns : 49995000

我不明白在用户定义线程的引用上调用时主线程如何休眠。

java multithreading java-threads thread-sleep
1个回答
0
投票

主线程和用户自定义线程没有区别。无论主线程是否仍在运行,所有非守护线程都可以运行完成。一旦所有非守护线程完成,守护线程就会被终止,但这不涉及任何interruptedExceptions。

只有在线程上调用中断方法时才会发生中断。

© www.soinside.com 2019 - 2024. All rights reserved.