本文介绍了Java线程不兼容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用Java编写线程的代码..但是线程不能同时工作..这是代码..



I have a code for thread execution in Java.. But the threads are not working concurrently.. Here is the code..

class Abc {

    public static void main(String[] ar){
        Mythread mt = new Mythread();
            mt.start();
            Mythread mt1 = new Mythread();
            mt1.start();
    }
}
class Mythread extends Thread{
    public void run(){
        for(int i = 0; i<= 9; i++){
            System.out.println(Thread.currentThread().getId() + " " + i);
        }
        try{
            Thread.sleep(1000);
        }
        catch(InterruptedException iex){

        }
    }
}



我希望输出为:

id1 0

id2 0

id1 1

id2 1

id1 2

id2 2

id1 3

id2 3

id1 4

id2 4

id1 5

id2 5

id1 6

id2 6

id1 7

id2 7

id1 8

id2 8

id1 9

id2 9



但我得到随机输出序列..请指出我做错了什么!



我尝试过:



实现并发Javathreads


I expect the output to be:
id1 0
id2 0
id1 1
id2 1
id1 2
id2 2
id1 3
id2 3
id1 4
id2 4
id1 5
id2 5
id1 6
id2 6
id1 7
id2 7
id1 8
id2 8
id1 9
id2 9

But I am getting random sequence of output..Please point out what I am doing wrong!

What I have tried:

Implementing concurrent Javathreads

推荐答案


这篇关于Java线程不兼容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 14:05