最近复习起当初学习多线程的demo,记录一下用来以后巩固这方面的技术。
/** * wait()和notify()实现生产消费模型 * * notify()唤醒不保证唤醒的是异类,也许是同类。如果写到两个类中可能出现假死进入WAITING状态 * @Author: gaomq * @Date: 2019-03-13 11:38 */ public class PC { private String lock; public PC(String lock){ this.lock=lock; } public void setValue(){ try { synchronized (lock){ if(!ValueObject.value.equals("")){ lock.wait(); } String value=System.currentTimeMillis()+""; System.out.println("set 值"+value); ValueObject.value=value; lock.notify(); } }catch (Exception e){ e.printStackTrace(); } } public void getValue(){ try { synchronized (lock){ if(ValueObject.value.equals("")){ lock.wait(); } System.out.println("get 值"+ValueObject.value); ValueObject.value=""; lock.notify(); } }catch (Exception e){ e.printStackTrace(); } } }
/** * 生产线程 * * @Author: gaomq * @Date: 2019-03-13 11:29 */ public class ThreadP extends Thread{ private PC pc; public ThreadP(PC pc){ this.pc=pc; } @Override public void run() { while (true){ pc.setValue(); } } }
/** * 消费线程 * * @Author: gaomq * @Date: 2019-03-13 11:30 */ public class ThreadC extends Thread{ private PC pc; public ThreadC(PC pc){ this.pc=pc; } @Override public void run() { while (true){ pc.getValue(); } } }
/** * 测试类 * * @Author: gaomq * @Date: 2019-03-13 11:31 */ public class Run { public static void main(String[] args) { String lock=new String("lock"); PC pc=new PC(lock); ThreadP p=new ThreadP(pc); ThreadC c=new ThreadC(pc); p.start(); c.start(); } }