要求:
1、消费者无数据消费则进入等待;
2、生产者满仓则进入等待;
代码如下:
package mythread; import java.text.SimpleDateFormat; import java.util.Date; import java.util.LinkedList; /** * 测试多线程,生产者和消费者 * Created by Administrator on 2018/5/15/015. */ @SuppressWarnings("all") public class ThreadTest { private static LinkedList<String> myQueue = new LinkedList<String>(); private static Object myLock = new Object(); public static class MySynchronizedTest implements Runnable{ public MySynchronizedTest(String myThreadName){ this.myThreadName = myThreadName; } private String myThreadName; public void setMyThreadName(String myThreadName) { this.myThreadName = myThreadName; } public String getMyThreadName() { return myThreadName; } private void doConsume() throws Exception{ synchronized (myLock){ if(ThreadTest.myQueue.isEmpty()){ System.out.println("消费者等待"); myLock.wait(); } String myFirst = myQueue.pop(); System.out.println(String.format("[%s]:%s",myThreadName,myFirst)); myLock.notify(); } } private void doProduce() throws Exception{ synchronized (myLock){ if(5 < myQueue.size()){ System.out.println("生产者等待"); myLock.wait(); } SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒"); myQueue.push(simpleDateFormat.format(new Date())); myLock.notify(); } } public void run() { try { if("Consume".equalsIgnoreCase(myThreadName)){ int count = 50; while (0 < count){ doConsume(); Thread.sleep(1000); --count; } }else { int count = 30; while (0 < count){ doProduce(); Thread.sleep(500); --count; } System.out.println("生产完毕"); } }catch (Exception e){ e.printStackTrace(); } } public void start(){ new Thread(this,myThreadName).start(); } }; public static void main(String[] args){ MySynchronizedTest producer = new MySynchronizedTest("Produce"); MySynchronizedTest consumer = new MySynchronizedTest("Consume"); producer.start(); consumer.start(); } }
运行结果:
[Consume]:2018年05月16日 13时51分47秒
[Consume]:2018年05月16日 13时51分48秒
[Consume]:2018年05月16日 13时51分49秒
[Consume]:2018年05月16日 13时51分50秒
[Consume]:2018年05月16日 13时51分51秒
[Consume]:2018年05月16日 13时51分52秒
[Consume]:2018年05月16日 13时51分53秒
生产者等待
[Consume]:2018年05月16日 13时51分53秒
生产者等待
[Consume]:2018年05月16日 13时51分54秒
生产者等待
[Consume]:2018年05月16日 13时51分55秒
生产者等待
[Consume]:2018年05月16日 13时51分56秒
生产者等待
[Consume]:2018年05月16日 13时51分57秒
生产者等待
[Consume]:2018年05月16日 13时51分58秒
生产者等待
[Consume]:2018年05月16日 13时51分59秒
生产者等待
[Consume]:2018年05月16日 13时52分00秒
生产者等待
[Consume]:2018年05月16日 13时52分02秒
生产者等待
[Consume]:2018年05月16日 13时52分03秒
生产者等待
[Consume]:2018年05月16日 13时52分04秒
生产者等待
[Consume]:2018年05月16日 13时52分05秒
生产者等待
[Consume]:2018年05月16日 13时52分06秒
生产者等待
[Consume]:2018年05月16日 13时52分07秒
生产者等待
[Consume]:2018年05月16日 13时52分08秒
生产者等待
[Consume]:2018年05月16日 13时52分09秒
生产者等待
[Consume]:2018年05月16日 13时52分10秒
生产完毕
[Consume]:2018年05月16日 13时52分11秒
[Consume]:2018年05月16日 13时51分52秒
[Consume]:2018年05月16日 13时51分51秒
[Consume]:2018年05月16日 13时51分50秒
[Consume]:2018年05月16日 13时51分49秒
[Consume]:2018年05月16日 13时51分48秒
消费者等待