ant_1024
2016-04-28 17:31
采纳率: 60%
浏览 2.9k
已采纳

在java多线程中用while循环和for循环输出的结果不同

public class Demo14 {

public static void main(String[] args) throws InterruptedException {

    MyThread2 thread2 = new MyThread2();
    Thread t = new Thread(thread2,"1");
    Thread t1 = new Thread(thread2,"2");
    t1.start();
    t.start();


}

}
class MyThread2 implements Runnable{
private int a = 5;
@Override
public void run() {
while(a>0){
a--;
System.out.println(Thread.currentThread

().getName()+":"+a);
}
}}

输出结果:
Thread-1:3
Thread-0:3
Thread-1:2
Thread-1:0
Thread-0:1

public class Demo14 {

public static void main(String[] args) throws InterruptedException {
    MyThread2 thread2 = new MyThread2();
    Thread t = new Thread(thread2);
    Thread t1 = new Thread(thread2);
    t1.start(); 
    t.start();
}

}

class MyThread2 implements Runnable{
private int a = 5;
@Override
public void run() {

    // TODO Auto-generated method stub
    for(int i = 0; i < a ; i++){
        System.out.println(Thread.currentThread

().getName()+":"+i);
}
}}

输出结果:
Thread-0:0
Thread-1:0
Thread-0:1
Thread-1:1
Thread-0:2
Thread-1:2
Thread-0:3
Thread-1:3
Thread-0:4
Thread-1:4


7条回答 默认 最新

相关推荐 更多相似问题