`

wait, notify及线程通讯机制

阅读更多

1) wait(), notify() 方法被调用的时候,只要外面没有被synchronized()罩住,编译可过,但是跑起来一定发生异常--- current thread not owner

 

2) wait(), notify()ref1一定要和synchronized(ref2)一致!两个ref必须是同一个东西,否则报错。

3) 处于wait()状态的Thread t1, 如果被别人调用了t1.interrupt(),立刻从wait()状态抛出interrupted异常,由此看来,线程通讯的另一种方法---wait(), interrupt()组合。当等待时间不确定的时候,只需要让某线程wait()在一个本地obj(保证永远不会被别人notify()起来),然后让外部线程通过interrupt()来唤醒

 

public class ThreadTest

{

      /**

       * @param args

       * @throws InterruptedException

       */

      public static void main(String[] args) throws InterruptedException

      {

            ThreadWait t5 = new ThreadWait();

            t5.start();

            // Doing alot of staff, here, maybe takes around 100ms, have no idea how long it will take.

            Thread.sleep(1000);

            t5.interrupt();  

      }

}

 

class ThreadWait extends Thread

{

      public void run()

      {

            Object obj = new Object();

            synchronized (obj)

            {

                  for (int i = 1; i <= 3; i++)

                  {

                        System.out.println("ThreadSleep : " + i + ".    " + this.getName());

                  }

                  try

                  {

                        obj.wait();//永远没有机会被notify(),只有等待被interrupt,interrupt之后,才会继续执行,

                        //因为我也不知道我要等待多长时间

                  }

                  catch (InterruptedException ignore){}

                  for (int i = 4; i <= 6; i++)

                  {

                        System.out.println("ThreadSleep : " + i + ".    " + this.getName());

                  }

            }

      }

}

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics