假设有一个仓库,只能放一个对象,需要完成:两个线程一个生产一个消费
生产者—>java.lang.Object@6865ca8a
消费者—>java.lang.Object@6865ca8a
生产者—>java.lang.Object@5d561924
消费者—>java.lang.Object@5d561924
…
代码实现
import java.util.ArrayList;
import java.util.List;
public class ThreadDemo {
public static void main(String[] args) {
// 仓库
List<Object> list = new ArrayList<>();
Thread producer = new Thread(new Producer(list));
Thread consumer = new Thread(new Consumer(list));
producer.setName("生产者");
consumer.setName("消费者");
producer.start();
consumer.start();
}
}
// 生产者
class Producer implements Runnable {
// 仓库
private List<Object> list;
public Producer(List<Object> list) {
this.list = list;
}
@Override
public void run() {
while (true) {
synchronized (list) {
// 如果仓库满了就等待
if (list.size() > 0) {
list.notify();
try {
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 如果没满,就生成
Object s = new Object();
System.out.println(Thread.currentThread().getName() + "--->" + s);
list.add(s);
}
}
}
}
// 消费者
class Consumer implements Runnable {
// 仓库
private List<Object> list;
public Consumer(List<Object> list) {
this.list = list;
}
// 消费者消费
@Override
public void run() {
while(true) {
synchronized (list) {
// 如果仓库空了就等待
if (list.size() == 0) {
list.notify();
try {
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 仓库有就消费
Object remove = list.remove(0);
System.out.println(Thread.currentThread().getName() + "--->" + remove);
}
}
}
}
线程交替打印奇偶数
package com.threadlocal;
public class PrintNum {
public static void main(String[] args) {
Thread single = new Thread(() -> {
int i = 0;
while (i <= 100) {
synchronized (PrintNum.class) {
// 如果此时为偶数,等待
if ((i & 1) == 0) {
PrintNum.class.notify();
try {
// 不加等待时间,最后一次wait不会被唤醒
PrintNum.class.wait(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
// 奇数时需要打印,偶数不打印
System.out.println(Thread.currentThread().getName() + "-->" + i);
}
i++;
}
}
});
Thread dou = new Thread(() -> {
int i = 0;
while (i <= 100) {
synchronized (PrintNum.class) {
// 如果此时为奇数,等待
if ((i & 1) == 1) {
PrintNum.class.notify();
try {
PrintNum.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
// 偶数时需要打印
System.out.println(Thread.currentThread().getName() + "-->" + i);
}
i++;
}
}
});
single.setName("奇数线程");
dou.setName("偶数线程");
single.start();
dou.start();
}
}
运行结果:
偶数线程-->0
奇数线程-->1
偶数线程-->2
奇数线程-->3
偶数线程-->4
奇数线程-->5
偶数线程-->6
奇数线程-->7
偶数线程-->8
奇数线程-->9
偶数线程-->10
奇数线程-->11
偶数线程-->12
奇数线程-->13
....