并发编程基础之wait以及notify的用法
Posted 格物致知
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了并发编程基础之wait以及notify的用法相关的知识,希望对你有一定的参考价值。
一:概念
线程通信中经常用到wait和notify,顾名思义,wait即让当前线程处于等待状态,notify通知锁对象
上的另一个线程被唤醒,这里的唤醒是指可以去争夺锁资源,nofityAll是唤醒该对象上面所有处于
wait状态的线程
二:示例
线程t2一运行就处于wait等待状态,然后线程t1运行notify,唤醒线程t2
/** * */ package com.day2; /** * @author Administrator * */ public class NotifyWaitThreadDemo { private int count; public static void main(String[] args) { NotifyWaitThreadDemo demo = new NotifyWaitThreadDemo(); Thread t1 = new Thread("t1") { public void run() { synchronized (demo) { for (int i = 0; i < 100; i++) { demo.count = i; if (demo.count == 50) { System.out.println(Thread.currentThread().getName()+"发出通知"); demo.notify(); } } } } }; Thread t2 = new Thread("t2") { public void run() { while (true) { synchronized (demo) { System.out.println(Thread.currentThread().getName() + "开始等待"); try { demo.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(Thread.currentThread().getName() + "跳出等待"); System.out.println("demo.count" + demo.count); break; } } }; t2.start(); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } t1.start(); } }
如果还有一个线程t3也处于wait状态,那么t1线程如果想唤醒t1和t3,就需要使用notifyAll
/** * */ package com.day2; /** * @author Administrator * */ public class NotifyWaitThreadDemo { private int count; public static void main(String[] args) { NotifyWaitThreadDemo demo = new NotifyWaitThreadDemo(); Thread t1 = new Thread("t1") { public void run() { synchronized (demo) { for (int i = 0; i < 100; i++) { demo.count = i; if (demo.count == 50) { System.out.println(Thread.currentThread().getName()+"发出通知"); //demo.notify(); demo.notifyAll(); } } } } }; Thread t2 = new Thread("t2") { public void run() { while (true) { synchronized (demo) { System.out.println(Thread.currentThread().getName() + "开始等待"); try { demo.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(Thread.currentThread().getName() + "跳出等待"); System.out.println("demo.count" + demo.count); break; } } }; Thread t3 = new Thread("t3") { public void run() { while (true) { synchronized (demo) { System.out.println(Thread.currentThread().getName() + "开始等待"); try { demo.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(Thread.currentThread().getName() + "跳出等待"); break; } } }; t2.start(); t3.start(); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } t1.start(); } }
运行结果:
t2开始等待 t3开始等待 t1发出通知 t3跳出等待 t2跳出等待 demo.count99
以上是关于并发编程基础之wait以及notify的用法的主要内容,如果未能解决你的问题,请参考以下文章
Java并发编程之二彻底理解Java的wait和Notify机制
JUC并发编程 -- 为什么需要wait/notify方法 & 原理之 wait / notify & wait() 和 notify() API介绍