一,问题描述
1,有两个线程,一个是读线程,一个是写线程。还有一个队列。现在要求编写一个程序,实现读线程从队列中读取数据出来。写线程往队列中写入数据。
二,实现的程序
import java.util.concurrent.LinkedBlockingDeque; //阻塞队列(BlockingQueue),Java包含实现阻塞列表的LinkedBlockingDeque类
import java.io.*;
public class ThreadTest {
public static void main(String []args) throws IOException{
final LinkedBlockingDeque<String> queue=new LinkedBlockingDeque<String>();
//final表示引用类型的地址不能改变了,就是queue=new LinkedBolck..是错的了。
new Thread(){ //往队列中写入数据
public void run()
{
BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));
String str=null;
while(true)
{
try{
str=reader.readLine();
if(str.equals("stop"))
{
try{
queue.put(str); //往队列中写入数据的方法是put(str)
}catch(InterruptedException e)
{
e.printStackTrace();
}
}
}catch(IOException e)
{
e.printStackTrace();
}
try{
queue.put(str);
}catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
}.start();
new Thread(){ //从队列中读取数据
public void run()
{
String str=null;
while(true)
{
try{
str=queue.take();//从队列中读取数据的方法是take()
}catch(InterruptedException e)
{
e.printStackTrace();
}
if(str.equals("stop"))
{
System.out.println(str);
break;
}
System.out.println(str);
}
}
}.start();
}
}
运行结果: