public class ThreadTest4 { public static void main(String[] args) { Runnable ru = new HelloThread1(); Thread t1 = new Thread(ru); Thread t2 = new Thread(ru); t1.start(); t2.start();
}
} class HelloThread1 implements Runnable { int i; @Override public void run() { int i = 0; while(true) { System.out.println("number :"+this.i++); try { Thread.sleep((long)(Math.random()*1000)); } catch (InterruptedException e) { e.printStackTrace(); } if(this.i == 50) break;
} System.out.println("我来测试!!!");
} } 输出结果
number :0 number :1 number :2 number :3 number :4 number :5 number :6 number :7 number :8 number :9 number :10 number :11 number :12 number :13 number :14 number :15 number :16 number :17 number :18 number :19 number :20 number :21 number :22 number :23 number :24 number :25 number :26 number :27 number :28 number :29 number :30 number :31 number :32 number :33 number :34 number :35 number :36 number :37 number :38 number :39 number :40 number :41 number :42 number :43 number :44 number :45 number :46 number :47 number :48 number :49 我来测试!!! 我来测试!!! 线程t1 和 线程t2 同时对 i 进程操作,肯定有某一个线程让i = 50 run方法终止,但是另外一个线程在执行循环,i的值变为51 ,不是死循环码,求解??求解释?????