Sleep示例分析
sleep让"当前线程"由“运行状态”进入到“休眠(阻塞)状态”,sleep结束,线程重新被唤醒时,它会由“阻塞状态”变成“就绪状态”,从而等待cpu的调度执行。
示例分析:
public class TestSleep { private static final Object lock = new Object(); public static void main(String[] args) { SleepThread t1 = new SleepThread("t1"); SleepThread t2 = new SleepThread("t2"); t1.start(); t2.start(); /** * sleep让当前线程休眠 * 让当前线程由“运行状态”进入到“休眠(阻塞)状态”,sleep结束,线程重新被唤醒时,它会由“阻塞状态”变成“就绪状态”,从而等待cpu的调度执行。 * sleep不会释放lock对象的锁 */ } static class SleepThread extends Thread { public SleepThread(String name) { super(name); } @Override public void run() { synchronized (lock){ for (int i = 0; i < 10; i++) { System.err.println(this.getName()+"___"+i); if (i%4==0){ System.err.println(this.getName()+"__sleep_"+i); try { sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } } } }