Java Thread(线程)案例详解sleep和wait的区别
?Java Thread(线程)案例详解sleep和wait的区别
http://www.cnblogs.com/DreamSea/archive/2012/01/16/SleepAndWaitDifferent.html区别
sleep()方法 sleep()使当前线程进入停滞状态(阻塞当前线程),让出CUP的使用、目的是不让当前线程独自霸占该进程所获的CPU资源,以留一定时间给其他线程执行的机会;F代码

/** * Thread sleep和wait区别 * @author DreamSea * 2012-1-15 */public class ThreadTest implements Runnable { int number = 10; public void firstMethod() throws Exception { synchronized (this) { number += 100; System.out.println(number); } } public void secondMethod() throws Exception { synchronized (this) { /** * (休息2S,阻塞线程) * 以验证当前线程对象的机锁被占用时, * 是否被可以访问其他同步代码块 */ Thread.sleep(2000); //this.wait(2000); number *= 200; } } @Override public void run() { try { firstMethod(); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) throws Exception { ThreadTest threadTest = new ThreadTest(); Thread thread = new Thread(threadTest); thread.start(); threadTest.secondMethod(); }}使用Wait()方法输出结果:【显示输出】
sleep()和wait()方法的区别已经讲解完毕,若对线程有兴趣的童鞋我在诺诺的问问:在main方法中最后行加入“System.out.println("number="+threadTest.number);”猜猜会输出什么结果。。。J