多个线程的执行顺序 [英] Execution order of multiple threads

查看:118
本文介绍了多个线程的执行顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有这种情况:

class Stack{

public void main{

ChildThread1 t1 = new ChildThread1;
ChildThread1 t2 = new ChildThread1;
ChildThread1 t3 = new ChildThread1;

//then we make some ChildThread2 objects and some ChildThread3 objects

ChildThread2 s1 = new ChildThread2;
//...

ChildThread3 v1 = new ChildThread3;
//...

//now we let all threads start in mix order
t1.start();
v1.start();
//...

SOP("All threads are ready");

//then we let them run with join()
t1.join();
t2.join();
t3.join();

s1.join();
//...

v1.join();
//...

每种类型的线程在打印时都会打印自己的唯一语句运行。

Each type of thread prints its own unique statement when it is running.

我注意到每次执行程序时,输出总是不同的。例如,来自ChilThread1 t1的语句将在输出的中间打印而不是开始(因为t1首先开始)或者所有线程都准备好的语句将在线程执行的中间弹出(例如:ChildThread2是'所有线程都已准备就绪跑步

I noticed that every time I execute the program, the output is always different. For example, a statement from ChilThread1 t1 will print in the middle of output instead of beginning (since t1 starts first) or the statement "all threads are ready" will pop in middle of thread execution (Example: ChildThread2 is 'all threads are ready' running )

所以我试图找到答案,我找到了这个网站: http://www.avajava.com/tutorials/lessons/how-do-i-use-threads-join-method。 html
该网站基本上说当你使用start()时没有保证执行顺序

So I tried to find an answer and I found this site: http://www.avajava.com/tutorials/lessons/how-do-i-use-threads-join-method.html The site basically says there's no guarantee order of execution when you use start()

所以我认为这个奇怪的命令是正确的print是因为start()不保证执行顺序?这个理由是否也适用于所有线程已准备好的问题?

So am I right to assume that this weird order of prints is because start() does not guarantee order of execution? Will this reason also apply to 'all threads are ready' problem?

推荐答案

线程的全部意义在于它们可以被执行同时。如果你想确保完成任务的具体顺序,你要么不再使用线程,要么使用显式同步。

The whole point of threads is that they can be executed concurrently. If you want to ensure specific order in which things are done, you either have to move away from using threads, or use explicit synchronization.


所以我可以假设这种奇怪的打印顺序是因为start()不保证执行顺序吗?

So am I right to assume that this weird order of prints is because start() does not guarantee order of execution?

这是正确的。当你开始一个线程时,主线程和新创建的线程之间基本上存在竞争条件。这意味着没有任何关于两个线程之间发生事件的相对顺序的说法。如果您想确保特定订购,请使用同步。

That's right. When you start a thread, there's basically a race condition between the main thread and the newly created thread. This means that nothing can be said about the relative order in which things happen between the two threads. If you want to ensure specific ordering, use synchronization.

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

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