【多线程】多线程交互+生产者消费者案例
【多线程】多线程交互生产者消费者案例1wait、notify、notifyAll2生产者消费者问题1wait、notify、notifyAllwait方法和notify方法并不是Thread线程上的方法它们是Object上的方法所有的Object都可以被用来作为同步对象。wait()的意思是 让占用了这个同步对象的线程临时释放当前的占用并且等待。 所以调用wait是有前提条件的一定是在synchronized块里否则就会出错。notify() 的意思是通知一个等待在这个同步对象上的线程你可以苏醒过来了有机会重新占用当前对象了。notifyAll() 的意思是通知所有的等待在这个同步对象上的线程你们可以苏醒过来了有机会重新占用当前对象了。2生产者消费者问题1-使用栈来存放数据并且把栈改造为支持线程安全。当栈内的数据为0的时候访问pull方法的线程就会等待不为0的时候所有访问pull方法的线程都会被唤醒。当栈内的数据满的时候访问push方法的线程就会等待当不是满的时候所有访问push方法的线程都会被唤醒。2-提供一个生产者线程类生产随机大写字符压入栈堆3-提供一个消费者线程类从栈堆中弹出字符并打印4-提供一个测试类使两个生产者和三个消费者线程同时运行publicclassMyStackT{LinkedListTvaluesnewLinkedListT();//自定义方法内嵌栈的方法等于把栈的方法addLast改造成线程安全方法push//如过栈满了就通知线程等待没满就唤醒线程继续存放publicsynchronizedvoidpush(Tt){while(values.size()200){try{this.wait();}catch(InterruptedExceptione){e.printStackTrace();}}this.notifyAll();values.addLast(t);}//自定义方法内嵌栈的方法等于把栈的方法removeLast改造成线程安全方法pull//如果栈空了就通知线程等待有值了就唤醒线程继续获取publicsynchronizedTpull(){while(values.isEmpty()){try{this.wait();}catch(InterruptedExceptione){e.printStackTrace();}}this.notifyAll();returnvalues.removeLast();}publicTpeek(){returnvalues.getLast();}}publicclassProducerThreadextendsThread{privateMyStackCharacterstack;publicProducerThread(MyStackCharacterstack,Stringname){super(name);this.stackstack;}Overridepublicvoidrun(){while(true){charcrandomChar();System.out.println(this.getName() 压入c);stack.push(c);try{Thread.sleep(100);}catch(InterruptedExceptione){e.printStackTrace();}}}publiccharrandomChar(){return(char)(Math.random()*(Z1-A)A);}}publicclassConsumerThreadextendsThread{privateMyStackCharacterstack;publicConsumerThread(MyStackCharacterstack,Stringname){super(name);this.stackstack;}Overridepublicvoidrun(){while(true){charcstack.pull();System.out.println(this.getName() 弹出c);stack.push(c);try{Thread.sleep(100);}catch(InterruptedExceptione){e.printStackTrace();}}}}publicclassTestThreadProductConsume{publicstaticvoidmain(String[]args){MyStackCharacterstacknewMyStack();for(inti0;i5;i){newProducerThread(stack,生产者i).start();}for(inti0;i5;i){newConsumerThread(stack,消费者i).start();}}}