多线程之wait与notify实现线程间通信
一个线程执行相加的操作,相加结束后,通知另一个线程打印。
?
?
/* * To change this template, choose Tools | Templates * and open the template in the editor. */package com.xiva.baseKnowledge;import java.util.concurrent.TimeUnit;import java.util.logging.Level;import java.util.logging.Logger;/** * * @author Administrator */public class MutiThread { public static int count = 0; //public static boolean mutex = true; public synchronized void print() { System.out.println(count); } public synchronized void add(int i) { count = count + i; System.out.println("add"); } public static void main(String[] args) { MutiThread mThread = new MutiThread(); PrintThread pThread = new PrintThread(mThread); AddThread addThread = new AddThread(pThread); addThread.start(); pThread.start(); }}class PrintThread extends Thread { private final MutiThread mThread; private volatile boolean startP = false; public PrintThread(MutiThread mThread) { this.mThread = mThread; } public MutiThread getMThread(){ return this.mThread; } public synchronized void notifyPrint(){ startP = true; notify(); } public synchronized void print(){ if(startP){ mThread.print(); startP = false; } else{ try { wait(); } catch (InterruptedException ex) { Logger.getLogger(AddThread.class.getName()).log(Level.SEVERE, null, ex); } } } @Override public void run() { while (true) { print(); } }}class AddThread extends Thread { private final PrintThread pThread; public AddThread(PrintThread pThread) { this.pThread = pThread; } @Override public void run() { for (int i = 1; i < 1000; i++) { try { //Thread.sleep(5000); TimeUnit.SECONDS.sleep(5); } catch (InterruptedException ex) { Logger.getLogger(MutiThread.class.getName()).log(Level.SEVERE, null, ex); } pThread.getMThread().add(i); pThread.notifyPrint(); } }}?
调用notifyPrint方法通知另一个线程启动打印。