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

在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条回答

      报告相同问题?

      相关推荐 更多相似问题

      悬赏问题

      • ¥15 用MATLAB解决问题,需要代码
      • ¥45 关于C语言设计井字棋游戏问题的实现
      • ¥20 vuforia的Unity3D开发,模型附上特效后大量报错
      • ¥35 Python实现文本关键词提取
      • ¥20 如何使用c++语言完成实验仪器管理系统
      • ¥15 请问Unity使用Magica Cloth插件怎么调整散兵的帘子和振袖比较好?
      • ¥15 请问为什么原神模型导入Unity做动画默认姿势会站不直?
      • ¥15 ld: cannot open C:\Program: No such file or directory
      • ¥15 请问汏佬要怎么访问这种过滤了post和get的php内容?
      • ¥15 C语言调用python脚本出现Debug Assertion Failed错误