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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© DOOR 中级黑马   /  2013-12-31 23:09  /  1036 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 DOOR 于 2014-1-4 18:03 编辑
  1. class StopThread implements Runnable//1
  2. {
  3.         private boolean flag = true;
  4.         public void run()//2
  5.         {
  6.                 while(flag)//3
  7.                 {
  8.                         try
  9.                         {
  10.                                 wait();
  11.                         }
  12.                         catch (InterruptedException e)
  13.                         {
  14.                                 System.out.println(Thread.currentThread().getName()+"....Exception");
  15.                         }
  16.                         System.out.println(Thread.currentThread().getName()+"....run");
  17.                 }
  18.         }
  19.         public void changeFlag()//6
  20.         {
  21.                 flag=false;
  22.         }
  23. }
  24. class  StopThreadDemo
  25. {
  26.         public static void main(String[] args)
  27.         {
  28.                 StopThread st = new StopThread();//4
  29.                 Thread t1 = new Thread(st);
  30.                 Thread t2 = new Thread(st);
  31.                 t1.start();
  32.                 t2.start();

  33.                 int num = 0;//5
  34.                 while(true)
  35.                 {
  36.                         if (num++ == 60)
  37.                         {
  38.                                 st.changeFlag();
  39.                                 break;
  40.                         }
  41.                         System.out.println(Thread.currentThread().getName()+"........"+num);
  42.                 }
  43.         }
  44. }
复制代码
为什么我写的这个特殊情况线程没有挂起来,求解

评分

参与人数 1技术分 +1 收起 理由
乔兵 + 1

查看全部评分

1 个回复

倒序浏览
本帖最后由 776699 于 2014-1-1 01:18 编辑

在t1,t2,main线程运行时,当t1,t2,线程抢到执行权时,t1,t2,等待挂起,main主线程执行,完以后,t1,t2 并没有被唤醒,所以  st.changeFlag();不会被执行!!处于等状态。
解决方案:可以用interrupt() 让处于冻结的状态运行,t1.interrupt();t2,interrupt().
这样就可以中断线程。

因为你这个是多线程,你这个run方法里最好,加一个synchronized ,防止监控器 异常错误。

评分

参与人数 1技术分 +1 收起 理由
乔兵 + 1

查看全部评分

回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马