线程的协作

 
 
 
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();
 
    }
}
 
梦里不知身是客,一晌贪欢。
原文地址:https://www.cnblogs.com/dccmmtop/p/5710156.html