java多线程并发两个或多个线程?

时间:2015-08-14 04:05:50

标签: java multithreading concurrency

那么, 我想了解这个案子。当我创建两个共享同一个Runnable实例的线程时。为什么这个订单?

Hello from Thread t 0
Hello from Thread u 1
Hello from Thread t 2
Hello from Thread t 4
Hello from Thread u 3 <----| this is not in order
Hello from Thread u 6
Hello from Thread t 5 <----| this one too
Hello from Thread t 8
Hello from Thread t 9
Hello from Thread t 10

我将向您展示两个帖子的代码:

public class MyThreads {
    public static void main(String[] args) {
        HelloRunnerShared r = new HelloRunnerShared();              
        Thread t = new Thread(r,"Thread t");
                Thread u = new Thread(r,"Thread u");
        t.start();
                u.start();

    }    
}

最后,最后一个问题是,如果我正在运行这个线程,我知道他们没有按顺序运行但是。为什么一个帖子正在保持或打印一个无序的号码?

这是runnable的代码:

class HelloRunnerShared implements Runnable{
    int i=0;
    public void run(){
        String name = Thread.currentThread().getName();
        while (i< 300) {
            System.out.println("Hello from " + name + " " + i++);
        }
    }
}

我认为他们会被处理插入。这只是一个假设!!

谢谢!

1 个答案:

答案 0 :(得分:1)

为什么你认为线程应该按特定顺序执行?这是一种不确定的现象 - 无论哪个先安排,都先行。

如果您希望按固定顺序按顺序运行内容,请使用ExecutorService.invokeAll,无论其日程安排如何。