首页 > 编程 > Java > 正文

Java多线程的题目

2019-11-08 02:24:37
字体:
来源:转载
供稿:网友

一,问题描述 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(); }}

运行结果:

这里写图片描述


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表