多线程的wait()和sleep()

来源:互联网 发布:火车头采集js 编辑:程序博客网 时间:2024/06/10 20:08
package p2017_05_04_Thread;/** * Created by wq on 2017/5/4. */public class MultiThread {    public static void main(String[] args) throws InterruptedException {        new Thread(new Thread1()).start();        Thread.sleep(10);        new Thread(new Thread2()).start();    }    private  static class Thread1 implements Runnable{        @Override        public void run() {            //thread1和thread2用同一对象监视器,我们这里不能用this,由于这里的Thread1和下面的Thread2的this不是同一对象            //所以用MultiThread.class这个字节码对象,当虚拟机引用这个变量时,指向的都是同一个对象            synchronized (MultiThread.class){                System.out.println("enter Thread1.......");                System.out.println("Thread1 is waiting");                try {                    /**                     * 释放锁有两种方式,第一种是程序自然离开sychoronized代码块,第二种方法就是在sychoronized内部调用监视器                     * 的wait方法,这里使用wait方法释放锁                     */                    MultiThread.class.wait();                } catch (InterruptedException e) {                    e.printStackTrace();                }                System.out.println("thread is going on...");                System.out.println("thread1 is being over...");            }        }    }    private static class Thread2 implements  Runnable{        @Override        public void run() {            synchronized (MultiThread.class){                System.out.println("enter thread2.........");                System.out.println("thread2 notify other thread can release wait status..");                MultiThread.class.notify();                System.out.println("thread2 is sleeping ten millisecond...");                try {                    Thread.sleep(10);                } catch (InterruptedException e) {                    e.printStackTrace();                }                System.out.println("thead2 is going on");                System.out.println("thead2 is being over");            }        }    }}


运行结果如下图所示:



0 0
原创粉丝点击