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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 应国炎 黑马帝   /  2012-2-21 22:31  /  2140 人查看  /  6 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 应国炎 于 2012-2-22 09:56 编辑

毕老师第11天13讲中

Ticket t =new Ticket();

Thread t1= new Thread(t);
Thread t2= new Thread(t);

t1.start();
t.flag=false;
t2.start();


----------------------------------
执行run中的代码
if(flag)*** else **         

当执行到t.flag=false;后flag就一直是false了,那怎么还会交替执行if(flag)呢 ? 不解,谁能帮我讲一下



6 个回复

倒序浏览
没有人知道吗?{:soso_e103:}
回复 使用道具 举报
没有人知道吗?{:soso_e103:}
回复 使用道具 举报
我记得好像是在run方法的最后又把flag的值重新赋予为true的...
回复 使用道具 举报
李晓俊 发表于 2012-2-21 23:39
我记得好像是在run方法的最后又把flag的值重新赋予为true的...

没有重新赋值true
回复 使用道具 举报
  1. class Tra implements Runnable//extends Thread
  2. {
  3.         Object k=new Object();
  4.        
  5.         private int tickets=100;
  6.         boolean flag=true;
  7.         public void run()
  8.         {       
  9.                 if(flag)
  10.                 {
  11.                         while(true){

  12.                                                 synchronized(this)
  13.                                                         {
  14.                                                                 if(tickets>0)
  15.                                                                 {
  16.                                                                         try{Thread.sleep(10);}
  17.                                                                         catch(Exception e){}
  18.                                                                         System.out.println(Thread.currentThread().getName()+">>true>>"+tickets--);
  19.                                                                 }
  20.                                                         }
  21.                                                 }
  22.                 }
  23.                 else
  24.                         while(true)
  25.                         show();
  26.         }


  27.         public synchronized void show()
  28.         {
  29.                 if(tickets>0)
  30.                 {
  31.                         try{Thread.sleep(10);} catch(Exception e){}
  32.                         System.out.println(Thread.currentThread().getName()+">>false>>"+tickets--);
  33.                 }
  34.         }
  35. }






  36. public class Test
  37. {
  38.         public static void main(String args[])
  39.         {
  40.        
  41.                 Tra a=new Tra();
  42.                 Thread a1=new Thread(a,"a1");
  43.                 Thread a2=new Thread(a,"a2");
  44.                

  45.                 a1.start();
  46.                 try{Thread.sleep(10);}catch(Exception e){}
  47.                 a.flag=false;
  48.                 a2.start();
  49.         }
  50. }
复制代码
就是这个代码,谁解释一下???
回复 使用道具 举报
应国炎 黑马帝 2012-2-22 09:55:26
7#
{:soso_e129:}我自己找到原因了。
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马