zoukankan      html  css  js  c++  java
  • 线程的协作

     
     
     
    class Printer extends Thread
    {
        Vector task = new Vector();
        boolean runing = false;
        public void start()
        {
            runing = true;
            super.start();
        }
        public void run()
        {
            try
            {
                System.out.println("打印开始");
                while (runing)
                {
                    synchronized (this)
                    {
                        while ((task.size() == 0) && runing)
                        {
                            // 如果任务列表为空,而且线程还允许运行,则等待任务
                            System.out.println("没有什么内容可以打印了,等待中~~~~");
                            wait();
                            System.out.println("等待结束,准备打印内容");
                        }
                    }
                    if (runing)
                    {
                        //for(int i=0;i<task.size();i++)
                        System.out.println("任务是: " + task.lastElement());
                        task.remove(0);
                    }
                }
                System.out.println("打印结束");
            } catch (Exception e)
            {
                // TODO: handle exception
                e.printStackTrace();
            }
        }
     
        // 添加待打印的任务
        public void addTask(String s)
        {
            synchronized (this)
            {
                this.task.add(s);
                //this.task.add(s);
                //this.task.add(s);
                System.out.println("有内容可以打印了  唤醒打印线程");
                notify();
                // notifyAll();
            }
     
        }
     
        public void stopPrinter()
        {
            this.runing = false;
            synchronized (this)
            {
                System.out.println("停止打印线程 ");
                notify();
                // noitfyAll();
            }
        }
     
    }
     
    public class WaitNotify
    {
        public static void main(String[] args)
        {
            Printer printer = new Printer();
            printer.start();
            try
            {
                Thread.sleep(2000);
                for (int i = 0; i < 500; i++)
                {
                    Thread.sleep(1000);
                    printer.addTask("打印的i的结果是" + i);
                }
            } catch (InterruptedException e)
            {
                // TODO: handle exception
                e.printStackTrace();
            }
     
            printer.stopPrinter();
     
        }
    }
     
    梦里不知身是客,一晌贪欢。
  • 相关阅读:
    问题 E: C#判断回文字符串
    hdu 1130 How Many Trees? 【卡特兰数】
    The writing on the wall
    字典树的应用
    完全背包
    多重背包
    hdu 2191 【背包问题】
    最长上升子序列 and 最长公共子序列 问题模板
    hdu 4704 Sum 【费马小定理】
    费马小定理
  • 原文地址:https://www.cnblogs.com/dccmmtop/p/5710156.html
Copyright © 2011-2022 走看看