java多线程-sleep()方法和wait()方法

建议其看这篇文章,我只是搬运过来
https://www.cnblogs.com/hongten/p/hongten_java_sleep_wait.html

一、wait()

  • wait方法是Object的方法,是每一个类都拥有的一个方法
  • wait()方法一般和notify()/notifyAll()、synchronized(Object){..}一起用.同时Object.wait()必须在synchronized(Object object){}代码块中使用
  • 当调用wait方法的时候会释放对象锁,
  • 当调用notify()方法时只是会唤醒一个线程从等待队列转换到lock blocked pool中,等一个线程执行完毕以后,JVM会让线程获得对象锁

二、sleep()

  • sleep()是Thread类的静态方法,当调用此方法时,拥有的是一个Thread类锁,那么为什么在一个线程中调用此方法会阻止其他线程的运行??
  • 网上说sleep()不会释放对象锁,这个对象指的是谁??
  • 下面的例子中说在主线程中调用sleep()方法以后,其他线程就都会休眠,而在自己的线程中调用sleep()方法说不会释放对象锁,在Thread2获得的是SleepAndWait的对象锁,调用sleep()并不会释放synchronized锁住的那个锁就是SleepAndWait对象锁。
  • 但是在主线程中调用sleep方法的时候,那么主线程获得是哪个对象的锁,sleep()方法是一个静态方法,获得的肯定是一个类锁,而不是一个对象锁???
package java_lang_Object;

/**
 * Created by luckyboy on 2018/7/4.
 */
public class SleepAndWait {
    public static void main(String[] args){

        new Thread(new Thread1()).start();


        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(new Thread2()).start();
    }

}
class Thread1 implements Runnable{

    @Override
    public void run() {
       synchronized (SleepAndWait.class){
            System.out.println("thread1 has entered...");
            System.out.println("thread1 is waiting...");
            try{
                SleepAndWait.class.wait();              
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("thread1 is going on.....");
            System.out.println("thread1 is over.....");
        }

    }
}
class Thread2 implements Runnable{

    @Override
    public void run() {
        synchronized (SleepAndWait.class){
            System.out.println("thread2 has entered...");
            System.out.println("thread2 is sleeping...");

            SleepAndWait.class.notify();

            try{
                Thread.sleep(5000);

            }catch(Exception e){
                e.printStackTrace();
            }
            System.out.println("thread2 is going on.....");
            System.out.println("thread2 is over.....");
        }
    }
}

输出结果

thread1 has entered...
thread1 is waiting...
thread2 has entered...
thread2 is sleeping...
thread2 is going on.....
thread2 is over.....
thread1 is going on.....
thread1 is over.....

参考文章
https://www.cnblogs.com/hongten/p/hongten_java_sleep_wait.html

猜你喜欢

转载自blog.csdn.net/makeliwei1/article/details/80948451
今日推荐