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

以下是代码:
  1. package thread;

  2. public class Ticket3 implements Runnable
  3. {
  4. private int tick=100;
  5. Object obj=new Object();
  6. boolean flag=true;

  7. @Override
  8. public void run()
  9. {
  10. if(flag)
  11. {
  12. while(true)
  13. {
  14. synchronized(this)
  15. {
  16. if(tick>0)
  17. {
  18. try {
  19. Thread.sleep(10);
  20. } catch (InterruptedException e) {
  21. }
  22. }
  23. System.out.println(Thread.currentThread().getName() + "....code:"+ tick--);
  24. }

  25. }
  26. }

  27. else
  28. while(true)
  29. show();
  30. }
  31. public synchronized void show()
  32. {
  33. if (tick > 0) {
  34. try {
  35. Thread.sleep(10);
  36. } catch (InterruptedException e) {

  37. }
  38. System.out.println(Thread.currentThread().getName() + "....show:"+ tick--);
  39. }
  40. }
  41. }
复制代码
  1. package thread;

  2. public class ThisLockDemo2
  3. {
  4. public static void main(String[] args)
  5. {

  6. Ticket3 t=new Ticket3();

  7. Thread t1=new Thread(t);
  8. Thread t2=new Thread(t);


  9. t1.start();
  10. try {
  11. Thread.sleep(10);
  12. } catch (InterruptedException e) {

  13. }
  14. t.flag=false;
  15. t2.start();



  16. }

  17. }
复制代码
下面是我用MyEclipse打印的结果,竟然出现负数,找了半天不知是哪里出错了,吓人:
Thread-1....show:2
Thread-1....show:1
Thread-0....code:0
Thread-0....code:-1
Thread-0....code:-2

2 个回复

倒序浏览
本帖最后由 王程 于 2012-8-10 11:33 编辑
  1. package thread;

  2. public class Ticket3 implements Runnable
  3. {
  4. private int tick=100;
  5. Object obj=new Object();
  6. boolean flag=true;

  7. @Override
  8. public void run()
  9. {
  10. if(flag)
  11. {
  12. while(true)
  13. {
  14. synchronized(this)
  15. {
  16. if(tick>0)
  17. {
  18. try {
  19. Thread.sleep(10);
  20. } catch (InterruptedException e) {
  21. }
  22. //[color=Red]}[/color]主要问题在这里,这个括号表示if语句结束了,下面的语句不在if之中,当然无限循环了
  23. System.out.println(Thread.currentThread().getName() + "....code:"+ tick--);[color=Red]}[/color]}//这里添加就可以了

  24. }
  25. }

  26. else
  27. while(true){//这里加括号
  28. show();
  29. }
  30. }//这里加个括号,把show方法与if语句分离
  31. public synchronized void show()
  32. {
  33. if (tick > 0) {
  34. try {
  35. Thread.sleep(10);
  36. } catch (InterruptedException e) {

  37. }
  38. System.out.println(Thread.currentThread().getName() + "....show:"+ tick--);
  39. }
  40. }
  41. }
复制代码
回复 使用道具 举报
问题已经解决
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马