Unity C# Basics Review 32 - Threads (P475)

1. Create threads and background threads

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Threading;

public class Test : MonoBehaviour
{

    private void Start()
    {
        Thread t = new Thread(Run);
        t.Start();
        Debug.Log(t.IsBackground);//判断是否后台线程

        Thread t2 = new Thread(Run2);
        t2.Start();
        Debug.Log(t.IsBackground);//判断是否后台线程

        //Thread t = new Thread(new ThreadStart(Run));  //通过委托的形式创建线程
        //t.Start();
    }
    static void Run() 
    {
        while (true)
        {
            Debug.Log("aaa");
            Thread.Sleep(1000);
        }
    }
    static void Run2()
    {
        while (true)
        {
            Debug.Log("bbb");
            Thread.Sleep(1000);
        }
    }
}

 2. Several states of threads

public class Test : MonoBehaviour
{
    private void Start()
    {
        //线程的几种状态
        Thread t = new Thread(new ThreadStart(Run));  //通过委托的形式创建线程
        Debug.Log("Start前" + t.ThreadState);
        t.Start();
        Debug.Log("Start后" + t.ThreadState);
        t.Suspend();    //挂起
        Debug.Log("Suspend后" + t.ThreadState);
        t.Resume();     //启动
        Debug.Log("Resume后" + t.ThreadState);
        t.Abort();      //中止
        Debug.Log("Abort后" + t.ThreadState);
    }
    static void Run() 
    {
        while (true)
        {
            Debug.Log(DateTime.Now + "   " + DateTime.Now.Millisecond);
            Thread.Sleep(1000);
        }
    }
}

3. Thread pool

        Since the creation and destruction of threads requires a certain amount of overhead, excessive use of threads will cause a waste of memory resources.
For performance considerations, the concept of thread pools was introduced. The thread pool maintains a request queue. The thread pool
code extracts the task from the queue and then delegates it to a thread in the thread pool for execution. The thread will not be
destroyed This can not only execute the task in the background, but also reduce thread creation and The overhead caused by destruction.

       The thread pool defaults to background threads

ThreadPool.QueueUserWorkItem(Run,"AAA");

4. Task

        It is very simple to use the QueueUserWorkItem() method of ThreadPoolf to initiate an asynchronous thread execution. However, the
biggest problem with this method is that there is no built-in mechanism to let you know when the operation is completed. Is there a built-in
mechanism to obtain an asynchronous thread after the operation is completed? return value. For this purpose, you can use
the Task class in System.Threading.Tasks.

Pay attention to the order of execution

public class Test : MonoBehaviour
{
    private void Start()
    {
        Task t1 = new Task(Sum);
        t1.Start();
        //t1.Wait();  //加上wait,先打印结果,后打印aaa。Wait()会让其他线程先等待

        Debug.Log("aaa");  //先打印aaa(主线程),再打印结果(另外新开启的一个线程),新开启的线程需要计算时间
    }
    static void Sum() 
    {
        int s = 0;
        for (int i = 0; i < 100; i++)
        {
            s += i;
        }
        Debug.Log("结果是" + s);
    }
}

5. Use generic Task to calculate results

public class Test : MonoBehaviour
{
    private void Start()
    {
        //用泛型的Task来计算结果
        Task<int> t1 = new Task<int>(Sum);
        t1.Start();

        Debug.Log(t1.Result); //返回结果
    }
    static int Sum() 
    {
        int s = 0;
        for (int i = 0; i < 100; i++)
        {
            s += i;
        }
        return s;
    }
}

Guess you like

Origin blog.csdn.net/weixin_46711336/article/details/125662306