两个线程间的通讯
什么时候需要通信
多个线程并发执行时, 在默认情况下CPU是随机切换线程的,如果我们希望他们有规律的执行, 就可以使用通信, 例如每个线程执行一次打印
线程怎么通信
》如果希望线程等待, 就调用wait()
》如果希望唤醒等待的线程, 就调用notify();
notify是随机唤醒一个线程
notifyAll是唤醒所有线程
》这两个方法必须在同步代码中执行, 并且使用同步锁对象来调用
》如果方法中没有同步锁,会有异常IllegalMonitorStateException
public class demo1 { public static void main(String[] args) { MyTask task = new MyTask(); new Thread(() -> { while(true){ try { task.task1();//执行任务 } catch (InterruptedException e) { e.printStackTrace(); } try{ Thread.sleep(10); }catch(InterruptedException e){ e.printStackTrace(); } } }).start(); new Thread(){ @Override public void run() { while(true){ try { task.task2();//执行任务 } catch (InterruptedException e) { e.printStackTrace(); } try{ Thread.sleep(10); }catch(InterruptedException e){ e.printStackTrace(); } } } }.start(); } } /* wait和notify方法必须要在 同步代码方法内执行 如果方法内没有同步锁,会报非法监听异常 */ class MyTask{ int flag = 1;//标识 1:可以执行任务1,2:可以执行任务2 public synchronized void task1() throws InterruptedException { if(flag != 1){ this.wait();//当前线程等待 ,抛出中断异常 } System.out.println("1.银行信用卡自动还款任务..."); this.flag = 2; this.notify();//唤醒随机线程 } public synchronized void task2() throws InterruptedException { if(flag != 2){ this.wait();//当前线程等待 ,抛出中断异常 } System.out.println("2.银行储蓄卡自动结算利息任务..."); this.flag = 1; this.notify();//唤醒其他线程 } }

浙公网安备 33010602011771号