编写一个程序(由若干个类组成),该程序能够生成3个线程,其中2个线程向一个队列中写入数据,每次写入1个字节,
1个线程从队列中读出数据,一次2个字节。要求读写交替运行,并注意数据的同步,而且队列要借助数组实现。
该程序应该由四个类组成,一个控制类(main方法所在类),实现线程的创建与启动;两个线程类, 分别实现读数据与写数据;一个环形队列类,用于数据的存取。另外还应注意将synchronized关键字和wait/notify机制结合起来运用。
import java.util.LinkedList;
//这个是主控制类 public class Constroler {
public static void main(String[] args) {
MyQueue queue = new MyQueue(); WriteData w1 = new WriteData(queue, "线程1"); WriteData w2 = new WriteData(queue, "线程2"); ReadData r = new ReadData(queue, "线程3"); w1.start(); w2.start(); r.start(); } }
//这个是一个队列 class MyQueue { private LinkedList<Byte> list = null; public MyQueue() { list = new LinkedList<Byte>(); } public synchronized LinkedList<Byte> getQueue() { return list; } public synchronized void writeData(String threadName) { getQueue().addLast(Byte.parseByte("1")); System.out.println(threadName + "写入了一个字节 1, " + "现在队列里还有" + getQueue().size() + "个字节!"); notifyAll(); } public synchronized void readData(String threadName) { while(getQueue().size() - 2 < 0) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } getQueue().removeLast(); getQueue().removeLast(); System.out.println(threadName + "从队列拿走了2个字节, 现在还有" + getQueue().size() + "个字节!"); } }
//这个是写出线程,为了便于查看,我只是让它运行10次 class WriteData extends Thread{ private MyQueue queue = null; private String threadName; public WriteData(MyQueue queue, String threadName) { this.queue = queue; this.threadName = threadName; } @Override public void run() { for(int i=0; i<10; i++) { queue.writeData(threadName); } } }
//这个是读入线程,为了便于查看,我只是让它运行10次 class ReadData extends Thread{ private MyQueue queue = null; private String threadName; public ReadData(MyQueue queue, String threadName) { this.queue = queue; this.threadName = threadName; } @Override public void run() { for(int i=0; i<10; i++) { queue.readData(threadName); } } }
|