1,线程通信的概念:
多线程通过共享数据和线程相关API对线程执行过程一定的控制。
2,为什么要使用线程通信:
多个线程并发执行时,在默认情况下CPU是随机切换线程的,当我们需要多个线程来共同完成一件任务,并且我们希望他们有规律的执行,那么多线程之间需要一些协调通信,以此来帮我们达到多线程共同操作共享数据。
3,等待与唤醒的方法:(Object类中)
- 对应使用:同步代码块和锁对象;
(这些方法都要使用锁对象在同步代码块中调用),且需要2个或以上的线程;
注意:notify是唤醒另一个线程;
4,使用:
public class Text01 {public static void main(String[] args) {ArrayList<String> list = new ArrayList<>();//生产者new Thread(new Runnable() {@Overridepublic void run() {int number = 1;while (true) {//使用同步代码块用list集合对象作为锁;synchronized (list) {if (list.size() > 0) {//唤醒另一个线程(消费者)list.notify();try {//休眠list.wait();} catch (InterruptedException e) {e.printStackTrace();}}else {//设置延迟,延缓输出try {Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}//添加到集合list.add("包子"+number);number++;System.out.println("厨师生产了:"+list);//唤醒消费者list.notify();}}}}}).start();//消费者new Thread(new Runnable() {@Overridepublic void run() {while (true) {//使用同步代码块并使用list集合对象作为锁synchronized (list) {if (list.size()==0) {//唤醒生产者list.notify();try {list.wait();} catch (InterruptedException e) {e.printStackTrace();}}else {//移除String remove = list.remove(0);System.out.println("吃货吃掉了:"+remove);//吃完了,然后唤醒生产者list.notify();}}}}}).start();}}
