- Wait的作用
- 是让当前线程从运行状态到休眠状态
- notify的作用
- 是让当前线程从休眠状态到运行状态
- 如何停止线程
- 使用退出标志,使线程正常退出,也就是当run方法完成后线程终止
- 使用stop方法强行终止线程(不推荐使用,因为stop和suspend、resume一样,也可能发生不可预料的结果)。
- 使用interrupt方法中断线程。
- interrupt的作用
- 当对阻塞状态的线程调用interrupt方法时(处于阻塞状态的线程是调用sleep, wait, join 的线程),会抛出InterruptException异常,停止线程
- 线程之间的通讯
- 使用synchronized、notify()、wait()、notifyAll()进行线程之间的通讯
- Sleep()和wait()的区别
- Sleep()不会释放锁的资源、wait()会释放锁的资源
- Sleep()是时间到了就会被唤醒
- Wati()可以又notify()唤醒
- Lock锁和synchronized同步锁的区别
- Lock锁属于手动控制 灵活性好
- Synchronized同步锁属于自动控制 不利于扩展
- Lock锁的方法
- public Lock lock = new ReentrantLock(); // 创建锁对象 多个线程锁对象需一致
- Condition condition = lock.newCondition(); // 创建 condition对象 多个线程condition对象需一致
- Lock.lock(); // 上锁
- condition.await() ; //等待
- condition.signal() ; // 唤醒
- Lock.unlock(); // 释放锁资源
-
import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * 多线程之间通讯 * Create by wangxb * 2019-05-14 21:38 */ // 水果 class Fruit{ public String name; public String color; public boolean flag = false; public Lock lock = new ReentrantLock(); // 创建锁对象 多个线程的锁对象需一致 } // 生产者 class Producer implements Runnable{ private Fruit fruit; public Condition condition; public Producer(Fruit fruit, Condition condition){ this.fruit = fruit; this.condition = condition; } @Override public void run() { int i = 0; while (true){ fruit.lock.lock(); // 开始上锁 if (fruit.flag){ try { condition.await(); // 等待 } catch (InterruptedException e) { e.printStackTrace(); } }else{ if (i == 0){ fruit.name = "香蕉"; fruit.color = "黄色"; }else{ fruit.name = "辣椒"; fruit.color = "红色"; } i = (i+1)%2; fruit.flag = true; System.out.println("生产者生产了 "+fruit.color+" 的 "+fruit.name+"---"+i); condition.signal(); // 唤醒另外线程 fruit.lock.unlock(); // 释放锁 } } } } // 消费者 class Consumer implements Runnable { private Fruit fruit; public Condition condition; public Consumer(Fruit fruit, Condition condition){ this.fruit = fruit; this.condition = condition; } @Override public void run() { while (true){ fruit.lock.lock(); if (!fruit.flag) { try { condition.await(); } catch (InterruptedException e) { e.printStackTrace(); } }else{ System.out.println("消费者拿走了 "+fruit.color+" 的 "+fruit.name); fruit.flag = false; } condition.signal(); fruit.lock.unlock(); } } } public class Test { public static void main(String[] args) { Fruit fruit = new Fruit(); Condition condition = fruit.lock.newCondition(); Producer producer = new Producer(fruit, condition); Consumer consumer = new Consumer(fruit, condition); Thread t1 = new Thread(producer); Thread t2 = new Thread(consumer); t1.start(); t2.start(); } }