多线程的wait()和sleep()

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");
            }
        }
    }
}


运行结果如下图所示:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值