package com.www.java3;
/**
* 线程通信例子:使用两个线程交替打印1-100
* 三个方法:
* 1.wait():一旦执行此方法,线程进入阻塞状态,并释放同步监视器
* 2.notify():一旦执行此方法,唤醒被wait阻塞的一个线程,如果有多个线程被wait,则唤醒优先级最高的那个
* 3.notifyAll():唤醒所有被wait阻塞的线程
*
* 说明:
* 1.wait()、notify()、notifyAll()只能出现在同步代码块,同步方法中(lock不行)
* 2.三个方法的调用者必须是同步代码块或者同步方法中的同步监视器
* 3.三个方法定义在Object类中
* @author www
* @creat 2022-{MONTH}-{DAY}
*/
class Number implements Runnable{
private int num = 1;
@Override
public void run() {
while(true){
synchronized (this) {
notify();
if(num <= 100){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + num);
num++;
try {
//使调用wait()方法的线程进入阻塞状态
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}else break;
}
}
}
}
public class CommunicationTest {
public static void main(String[] args) {
Number number = new Number();
Thread t1 = new Thread(number);
Thread t2 = new Thread(number);
t1.setName("线程一");
t2.setName("线程二");
t1.start();
t2.start();
}
}
package com.www.java3;
/**
*
* @author www
* @creat 2022-{MONTH}-{DAY}
*/
class Clerk{
private int productCount = 0;
public synchronized void produceProduct() {
if(productCount < 20){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
productCount++;
System.out.println(Thread.currentThread().getName() + "开始生产第" + productCount + "个产品");
notify();
}else {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public synchronized void consumeProduct() {
if(productCount > 0){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "开始消费第" + productCount + "个产品");
productCount--;
notify();
}else {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Productor extends Thread{
private Clerk clerk;
public Productor(Clerk clerk){
this.clerk = clerk;
}
@Override
public void run() {
System.out.println(getName() + "开始生产产品");
while (true){
clerk.produceProduct();
}
}
}
class Customer extends Thread{
private Clerk clerk;
public Customer(Clerk clerk){
this.clerk = clerk;
}
@Override
public void run() {
System.out.println(getName() + "开始消费产品");
while (true){
clerk.consumeProduct();
}
}
}
public class ProductTest {
public static void main(String[] args) {
Clerk clerk = new Clerk();
Productor p1 = new Productor(clerk);
Customer c1 = new Customer(clerk);
p1.setName("生产者1");
c1.setName("消费者1");
p1.start();
c1.start();
}
}