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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 菠菜树 中级黑马   /  2015-2-23 21:54  /  1175 人查看  /  8 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

  1. public class Test_7 implements Runnable{

  2.         public static void main(String[] args) {
  3.                 Test_7 t7=new Test_7();
  4.                 Thread t7t=new Thread(t7);
  5.                 t7t.start();
  6.                 try{
  7.                         Thread.sleep(2000);
  8.                 }
  9.                 catch(InterruptedException e){}
  10.                 System.out.println("In the main(),interrupt the other thread !");
  11.                 t7t.interrupt();
  12.                 System.out.println("In the main(),quit !");
  13.         }
  14.         public void run(){
  15.                 try{
  16.                         System.out.println("In the run(),this thread sleep 20S !");
  17.                         Thread.sleep(20000);
  18.                         System.out.println("In the run(),this thread is go on !");
  19.                 }
  20.                 catch(InterruptedException e){
  21.                         System.out.println("In the run(),this thread is interrupted !");
  22.                         return;
  23.                 }
  24.                 System.out.println("In the run(),this thread is go to finish !");
  25.                 System.out.println("In the run(),this thread quit in normal !");
  26.         }
  27. }
复制代码

书上的结果是:
In the run(),this thread sleep 20S !
In the main(),interrupt the other thread !
In the run(),this thread is interrupted !
In the main(),quit !

我的结果是:
In the run(),this thread sleep 20S !
In the main(),interrupt the other thread !
In the main(),quit !
In the run(),this thread is interrupted !

8 个回复

倒序浏览
这个跟你程序没关系 ,   跟你的cpu有关系,你开启了两个线程,先执行那个线程后执行那个线程cpu说了算。
书上的是Thread-0线程先睡了,也就先醒,
你的是主线程先睡了,主线程现醒。
你的主线程瞬间执行到了sleep
书上的执行到start,cpu执行权被Thread-0抢走了
回复 使用道具 举报
心镜逝水 来自手机 中级黑马 2015-2-24 11:23:48
藤椅
,,,,。,。。。
回复 使用道具 举报
这是Cpu执行权的问题。你可以在t7t.interrupt();下面加上一行Thread.sleep(longtime);就和书上一样了
回复 使用道具 举报
linuxpara910829 发表于 2015-2-24 01:43
这个跟你程序没关系 ,   跟你的cpu有关系,你开启了两个线程,先执行那个线程后执行那个线程cpu说了算。
  ...

明白了,非常谢谢,:handshake
回复 使用道具 举报
㏒假™面具 发表于 2015-2-24 18:13
这是Cpu执行权的问题。你可以在t7t.interrupt();下面加上一行Thread.sleep(longtime);就和书上一样了 ...

恩恩,是的,只要让线程稍微休眠一下就解决了,谢谢:handshake
回复 使用道具 举报
心镜逝水 发表于 2015-2-24 11:23
,,,,。,。。。

灌水小心被扣分。。。:lol

点评

,,,,,,,,不要回复我呦,小心也扣你的分  发表于 2015-2-27 08:12
回复 使用道具 举报
linuxpara910829 发表于 2015-2-24 01:43
这个跟你程序没关系 ,   跟你的cpu有关系,你开启了两个线程,先执行那个线程后执行那个线程cpu说了算。
  ...

是的,回答的不错哦:D
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马