zoukankan      html  css  js  c++  java
  • 多线程 sleep和wait的区别

    
    

    对于sleep()方法,我们首先要知道该方法是属于Thread类中的。而wait()方法,则是属于Object类中的。

    
    

    sleep()方法导致了程序暂停执行指定的时间,让出cpu该其他线程,但是他的监控状态依然保持者,当指定的时间到了又会自动恢复运行状态。

    
    

    在调用sleep()方法的过程中,线程不会释放对象锁。

    
    

    而当调用wait()方法的时候,线程会放弃对象锁,进入等待此对象的等待锁定池,只有针对此对象调用notify()方法后本线程才进入对象锁定池准备


    3 public class ThreadTest { 4 5 public static void main(String[] args) 6 { 7 Thread t1=new Thread(new Thread1()); 8 t1.start(); 9 try 10 { 11 Thread.sleep(500); 12 } 13 catch(Exception e) 14 { 15 e.printStackTrace(); 16 } 17 Thread t2=new Thread(new Thread2()); 18 t2.start(); 19 } 20 21 private static class Thread1 implements Runnable 22 { 23 @Override 24 public void run() 25 { 26 synchronized(ThreadTest.class) 27 { 28 System.out.println("Thread1 start"); 29 System.out.println("thread1 is waiting..."); 30 try 31 { 32 ThreadTest.class.wait(); 33 } 34 catch(Exception e) 35 { 36 e.printStackTrace(); 37 } 38 System.out.println("thread1 is going on"); 39 System.out.println("thread1 is over"); 40 } 41 } 42 } 43 private static class Thread2 implements Runnable 44 { 45 @Override 46 public void run() 47 { 48 synchronized(ThreadTest.class) 49 { 50 System.out.println("Thread2 start"); 51 System.out.println("thread2 is waiting..."); 52 ThreadTest.class.notify(); 53 try 54 { 55 Thread.sleep(500); 56 } 57 catch(Exception e) 58 { 59 e.printStackTrace(); 60 } 61 System.out.println("thread2 is going on"); 62 System.out.println("thread2 is over"); 63 } 64 } 65 } 66 67 }
  • 相关阅读:
    10个迷惑新手的Cocoa,ObjectiveC开发难点和问题
    如何成为Android高手
    利用ModalViewController切换View
    自定义导航栏的返回按钮(xcode)
    iphone开发笔记和技巧总结(原址持续更新)
    axis2出现错误
    NYOJ 214(二分插入)
    NYOJ 17(LIS转为LCS,但是MLE)
    NYOJ 214(LIS二分插入)
    NYOJ 36(增量法解决LCS)
  • 原文地址:https://www.cnblogs.com/mingyao123/p/7233341.html
Copyright © 2011-2022 走看看