[Java] Java正常运行和Debug时候执行结果不一样 →→→→→进入此内容的聊天室

来自 , 2020-10-11, 写在 Java, 查看 148 次.
URL http://www.code666.cn/view/f197002b
  1. public class TestMain {
  2.         public static void main(String[] args) {
  3.                
  4.                 Runnable r1 = new MyThread();
  5.                 // 启动两个线程控制同一个对象r1
  6.                 Thread t1 = new Thread(r1);
  7.                 Thread t2 = new Thread(r1);
  8.                 t1.start();
  9.                 t2.start();
  10.                
  11.         }
  12. }
  13. class MyThread implements Runnable{
  14.         int i;
  15.         public void run() {
  16.                
  17.                 while(true){
  18.                         System.out.println(i++);                       
  19.                         try {
  20.                                 long tmp = (long)((Math.random())*1000);
  21.                                 Thread.sleep(tmp);
  22.                         } catch (InterruptedException e) {
  23.                                 e.printStackTrace();
  24.                         }
  25.                         if( i == 3 ){
  26.                                 // Debug的时候会有一个线程的i值不会等于3(也就不会break)
  27.                                 // 正常运行的时候,两个线程都会break
  28.                                 // 【问题:】为什么Debug的时和正常运行的情况不一样呢?
  29.                                 System.out.println(" i = 3");
  30.                                 break;
  31.                         }
  32.                 }
  33.         }
  34. }//源代码片段来自云代码http://yuncode.net
  35.                        

回复 "Java正常运行和Debug时候执行结果不一样"

这儿你可以回复上面这条便签

captcha