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();
     
        }
    }
     
    梦里不知身是客,一晌贪欢。
  • 相关阅读:
    PAIP HTML的调试与分析工具
    paip.输入法编程一级汉字1000个
    paip.DEVSUIT ADMIN 初次使用时出现两个LICENSE提醒
    int main(int argc,char *argv[])中参数的意义
    深入理解C语言小记
    曲线拟合的最小二乘法
    C51 bit和sbit的区别
    曲线拟合的最小二乘法
    有关verilog truncated value with size 32 to match size of target警告的处理
    C51 bit和sbit的区别
  • 原文地址:https://www.cnblogs.com/dccmmtop/p/5710156.html
Copyright © 2011-2022 走看看