关于Thread.sleep()的疑问:调用自定义线程引用为何让主线程休眠?
为什么调用自定义线程实例的sleep()方法会让主线程休眠?
Thread.sleep()方法会让执行它的线程进入休眠。但在下面的代码中,通过自定义线程的引用调用sleep()方法后,休眠的却是主线程,这让人困惑。
代码示例
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
问题核心
为什么通过自定义线程的引用调用sleep()方法,休眠的却是主线程?
解答
原因很直接:Thread.sleep()是一个静态方法。
不管你用哪个Thread实例去调用它,本质上都是调用了Thread类的静态方法,它只会让当前执行这段代码的线程进入休眠,和你用来调用的那个线程实例没有任何关系。
在你的代码里,thread.sleep(1000)这段代码是在主线程的main方法里执行的,所以休眠的自然是主线程。哪怕你用一个已经终止的线程实例去调用sleep(),休眠的依然是当前执行代码的线程。
Java设计这个静态方法的逻辑就是:sleep是让当前线程暂停,而不是让某个指定的线程暂停——毕竟直接控制另一个线程的休眠状态会涉及线程调度的安全性问题。
如果想要让自定义线程MyThread休眠,你需要在它的run()方法里调用Thread.sleep(),就像你代码里已经做的那样,这样休眠的才是MyThread线程本身。
内容的提问来源于stack exchange,提问作者Bh_04
相关产品推荐
相关产品推荐

