`
macheng365
  • 浏览: 28030 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

多线程问题

阅读更多
package com.thread;

public class PrintABCWith3Thread
{
    public static void main(String[] args) throws Exception
    {
        int[] look = new int[] { 100, 1 };
        Thread t1 = new Thread(new SubThread1(look), "Thread-1");
        Thread t2 = new Thread(new SubThread2(look), "Thread-2");
        Thread t3 = new Thread(new SubThread3(look), "Thread-3");
        t2.start();
        t3.start();
        t1.start();
    }
}


class SubThread1 implements Runnable
{
    int[] look = null;


    public SubThread1(int[] look)
    {
        this.look = look;
    }


    public void run()
    {
        synchronized (look)
        {
            while (look[0] > 0)
            {
                if (look[1] == 1)
                {
                    look[0]--;
                    System.out.println(Thread.currentThread().getName() + " 打印次数:"
                        + (100 - look[0]));
                    look[1] = 2;//告诉下一个由线程2来打印
                    look.notify();//打印完后自己释放资源鎖,并通知別人可以用鎖了
                }
                else
                //否则就必须等待锁等了,之後再來進行操作了
                {
                    try
                    {
                        look.wait();
                    }
                    catch (InterruptedException e)
                    {
                        e.printStackTrace();
                    }
                }

            }
        }
    }
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics