按楼主的代码多运行几次就会有不同的结果 我的机子上 如下
E:\java0217\practice2>java Threads1
0, 0, 2, 2, 4, 4, 6, 6,
E:\java0217\practice2>java Threads1
0, 2, 4, 6, 0, 2, 4, 6,
这是因为第二个线程还没等第一个线程执行完 把x的值重新写回主函数的x中时,第二个线程已经调用了主函数的最初的x值。
所以代码可以这样写- public class Threads1 {
- int x = 0;
- public class Runner implements Runnable {
- public void run() {
- int current;
- for (int i = 0; i < 4; i++) {
- current = x;
- System.out.print(current + ", ");
- x = current + 2;
- }
- }
- }
- public static void main(String[] args) {
- new Threads1().go();
- }
- public void go() {
- Runnable r1 = new Runner();
- Thread t1 = new Thread(r1);
- Thread t2 = new Thread(r1);
- t1.start();
- try
- {
- t1.join();
- }
- catch (Exception e)
- {
- }//等带线程t1执行完以后再去执行t2 就会得到楼主想要的结果
- t2.start();
- }
- }
复制代码 得到的输出为 0, 2, 4, 6, 8, 10, 12, 14,
|