A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 苏乞儿 中级黑马   /  2014-9-20 21:42  /  526 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

  1. <div class="blockcode"><blockquote>package cn.itcast.thread;
  2. /*
  3. * 线程终止的第二种情况,对于等待中的线程,用的是interrupt()方法终止线程。
  4. */
  5. public class InterruptThreadDemo2 {

  6.         public static void main(String[] args) {
  7.                 // TODO Auto-generated method stub
  8.                 InterruptThread2 it=new InterruptThread2(true);
  9.                
  10.                 Thread t=new Thread(it);
  11.                 t.start();
  12.                
  13.                 for(int i=0;i<100000;i++){
  14.                         if(i==99999)
  15.                                 it.flag=false;
  16.                 }
  17.         }

  18. }
  19. class InterruptThread2 implements Runnable{
  20.         boolean flag=true;
  21.         InterruptThread2(boolean flag){
  22.                 this.flag=flag;
  23.         }
  24.         public void run(){
  25.                 while(flag){
  26.                         //这个wait()方法为什么要方法同步下呢?跟谁同步啊,这是?
  27.                         synchronized(this){
  28.                                 try {
  29.                                         this.wait();
  30.                                 } catch (InterruptedException e) {
  31.                                 // TODO Auto-generated catch block
  32.                                         e.printStackTrace();
  33.                                 }
  34.                         System.out.println("run...");
  35.                         }
  36.                        
  37.                 }
  38.         }
  39. }
复制代码

老师举例的用中断线程中断处于wait状态下的线程时,上来就将wait()方法置于同步代买块下了,请问这时为什么呢?


0 个回复

您需要登录后才可以回帖 登录 | 加入黑马