Java线程不兼容 [英] Java thread not working concurrently

查看:69
本文介绍了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中的线程是线程调度程序可以做任何感觉喜欢做除非你使用join(),wait()等特定函数,甚至每次调用时都不能保证yield()方法运行,因为它更像是一个请求的类型,这就是你不能依赖它的原因。 />
所以,你期望的输出是可能的输出之一,但绝不是你唯一得到的。但这并不意味着你的线程没有同时运行。

希望这会有所帮助。

干杯。
Hey there,
The thing with threads in java is that the thread scheduler can do whatever it feels like doing unless you use specific functions like the join(), wait() etc even the yield() method isn't guaranteed to run each time you call it because it's more of a type a request which which is why you cannot depend on it.
So, the output which you were expecting is one of the possible outputs but by no means it's the only thing which you'll get. But this doesn't mean that your threads aren't running concurrently.
Hope this helps.
Cheers.


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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆