多线程:当我会用一个加入? [英] Multithreading: When would I use a Join?

查看:83
本文介绍了多线程:当我会用一个加入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I see online that it says I use myThread.Join(); when I want to block my thread until another thread finishes. (其中一件事我没有得到有关这就是如果我有多个线程)。

I see online that it says I use myThread.Join(); when I want to block my thread until another thread finishes. (One of the things I don't get about this is what if I have multiple threads).

但是总体来说,我只是不明白时,我会使用。加入()或者说,它是有用的情况。任何人都可以请解释这对我来说,我是一个小学四年级学生?很简单的解释,理解会得到我的答案投票。

But generally, I just don't get when I'd use .Join() or a condition that it's useful for. Can anyone please explain this to me like I'm a fourth grader? Very simple explanation to understand will get my answer vote.

推荐答案

让我们说你要开始的一些工作线程来执行某种,计算,然后做一些事后的所有结果

Let's say you want to start some worker threads to perform some kind of calculation, and then do something afterwards with all the results.

List<Thread> workerThreads = new List<Thread>();
List<int> results = new List<int>();

for (int i = 0; i < 5; i++) {
    Thread thread = new Thread(() => {
        Thread.Sleep(new Random().Next(1000, 5000));
        lock (results) {
            results.Add(new Random().Next(1, 10));
        }
    });
    workerThreads.Add(thread);
    thread.Start();
}

// Wait for all the threads to finish so that the results list is populated.
// If a thread is already finished when Join is called, Join will return immediately.
foreach (Thread thread in workerThreads) {
    thread.Join();
}

Debug.WriteLine("Sum of results: " + results.Sum());






噢,并且不使用随机像这一点,我只是想写一个最小的,容易理解的例子。它最终实际上不是,如果你创建新的随机实例太近的时候,因为种子是基于随机时钟


Oh yeah, and don't use Random like that, I was just trying to write a minimal, easily understandable example. It ends up not really being random if you create new Random instances too close in time, since the seed is based on the clock.

这篇关于多线程:当我会用一个加入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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