Java多线程的题目

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


    }

}

运行结果:

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值