多线程 wait notify


多线程线程(wait、notify)

 

***************************

相关方法

 

public class Object {

********
线程唤醒

    @HotSpotIntrinsicCandidate
    public final native void notify();

    @HotSpotIntrinsicCandidate
    public final native void notifyAll();


********
线程等待

    public final void wait() throws InterruptedException {
        wait(0L);
    }


    public final native void wait(long timeoutMillis) throws InterruptedException;
    public final void wait(long timeoutMillis, int nanos) throws InterruptedException {

说明:wait()、notify()、notifyAll()方法需要在同步语句里面使用;

wait()会立刻释放锁;notify() 、notifyAll()等到同步语句执行完释放锁

 

 

****************************

示例

 

class Test{

    synchronized void test(){
        try{
            System.out.println("进入同步方法test:"+System.currentTimeMillis());
            Thread.sleep(1000);
            this.wait();
            System.out.println("结束同步方法test:"+System.currentTimeMillis());
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    synchronized void test2(){
        try{
            System.out.println("进入同步方法test2:"+System.currentTimeMillis());
            this.notify();
            Thread.sleep(10000);
            System.out.println("结束同步方法test2:"+System.currentTimeMillis());
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

class Test1 implements Runnable{

    private Test test;

    Test1(Test test){
        this.test=test;
    }

    @Override
    public void run() {
        test.test();
    }
}

class Test2 implements Runnable{

    private Test test;

    Test2(Test test){
        this.test=test;
    }

    @Override
    public void run() {
        test.test2();
    }
}

public class ThreadTest6 {

    public static void main(String[] args){
        Test test=new Test();
        Test1 t1=new Test1(test);
        Test2 t2=new Test2(test);
        Thread thread=new Thread(t1);
        Thread thread2=new Thread(t2);

        thread.start();
        thread2.start();
    }
}

 

**************************

控制台输出

 

进入同步方法test:1568815070367
进入同步方法test2:1568815071390
结束同步方法test2:1568815081391
结束同步方法test:1568815081392

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值