线程的使用

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

public class Thread_Test : MonoBehaviour
{
    /// <summary>
    /// 信号灯
    /// </summary>
    private ManualResetEvent signal;


    private List<Thread> threadLst = new List<Thread>();

    private void Start()
    {
        signal = new ManualResetEvent(false);
        Fun1();
    }

    private void Fun1()
    {
        Thread thread01 = new Thread(Fun2);
        thread01.Start();
        threadLst.Add(thread01);

        Thread thread02 = new Thread(Fun3);
        thread02.Start(5);
        threadLst.Add(thread02);
    }

    private void Fun2()
    {
        for (int i = 0; i < 5; i++)
        {
            Thread.Sleep(1000);
            Debug.Log($"Fun2被执行:{i}");
            signal.WaitOne();   //线程等待
        } 
    }

    private void Fun3(object obj)
    {
        int len = (int)(obj);
        for (int i = 0; i < len; i++)
        {
            Thread.Sleep(1000);
            Debug.Log($"Fun3被执行:{i}");
        }
    }

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.R))
        {
            //暂停
            signal.Reset();
        }
        if (Input.GetKeyDown(KeyCode.S))
        {
            //恢复
            signal.Set();
        }
    }

    private void OnApplicationQuit()
    {
        if (threadLst.Count>0)
        {
            for (int i = 0; i < threadLst.Count; i++)
            {
                threadLst[i].Abort();
            }
        }
    }
}
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using UnityEngine;

public class Thread_时间 : MonoBehaviour
{
    private CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();

    private string timer;

    private int second = 120;

    private void Start()
    {
        ThreadPool.QueueUserWorkItem((obj) =>
        {
            UpdateTimer(cancellationTokenSource.Token);
        });
        ThreadPool.QueueUserWorkItem(CallBack, cancellationTokenSource.Token);
    }

    private void UpdateTimer(CancellationToken token)
    {
        while (second >= 0)
        {
            if (token.IsCancellationRequested)
            {
                Debug.Log("线程池操作被释放");
                break;
            }
            Thread.Sleep(1000);
            second--;
            timer = $"{second / 60}:{second % 60}";
            Debug.Log(timer);
        }
    }

    private void CallBack(object state)
    {
        Thread.Sleep(1000);
        PrintMessage("异步方法开始");
        CancellationToken token = (CancellationToken)state;
        UpdateTimer(token);
    }

    private void PrintMessage(string data)
    {
        int workThreadNum;
        int IOThreadNum;

        ThreadPool.GetAvailableThreads(out workThreadNum, out IOThreadNum);
        Debug.Log($"{data}\n CurrentThreadID is {Thread.CurrentThread.ManagedThreadId}\n" +
            $"CurrentThread is background:{Thread.CurrentThread.IsBackground.ToString()}\n" +
            $"workThreadNum is {workThreadNum}\n" +
            $"IOThreadNum is {IOThreadNum}");
    }


    private void OnApplicationQuit()
    {
        cancellationTokenSource.Cancel();
    }
}
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using UnityEngine;

public class Thread_线程池 : MonoBehaviour
{
    private static object lockObj = new object();
    ManualResetEvent manualResetEvent;

    private void Start()
    {
        ThreadPool.QueueUserWorkItem(Fun1);
    }

    private void Fun1(object state)
    {
        lock (lockObj)
        {
            Fun2();
        }
        manualResetEvent?.Set();
    }

    private void Fun2()
    {
        Debug.Log($"通过对象池被调用,当前的线程ID:{Thread.CurrentThread.ManagedThreadId}");
    }
}
using Common;
using System;
using System.Collections.Generic;

/// <summary>
/// 线程交叉访问助手类
/// 跨线程访问unityAPI
/// </summary>
public class ThreadCrossHelper : MonoSingleton<ThreadCrossHelper>
{
    class DelayedItem
    {
        public Action CurrentAction { get; set; }
        public DateTime Time { get; set; }
    }
    private List<DelayedItem> delayedItemLst;

    public override void Init()
    {
        base.Init();
        delayedItemLst = new List<DelayedItem>();
    }

    private void Update()
    {
        lock (delayedItemLst)
        {
            for (int i = delayedItemLst.Count - 1; i >= 0; i--)
            {
                if (delayedItemLst[i].Time <= DateTime.Now)
                {
                    if (delayedItemLst[i].CurrentAction != null)
                    {
                        delayedItemLst[i].CurrentAction();
                        delayedItemLst.RemoveAt(i);
                    }
                }
            }
        }
    }

    /// <summary>
    /// 在主线程执行
    /// </summary>
    public void ExecuteOnMainThread(Action cb, float delay = 0f)
    {
        lock (delayedItemLst)
        {

            var item = new DelayedItem()
            {
                CurrentAction = cb,
                Time = DateTime.Now.AddSeconds(delay)
            };
            delayedItemLst.Add(item);
        }
    }
}

  • 7
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Python中,多线程是一种并发编程技术,允许一个程序同时执行多个任务,每个任务在单独的线程中运行。使用Python的内置`threading`模块可以轻松地创建和管理线程。以下是使用Python多线程的基本步骤: 1. 导入`threading`模块:这是开始多线程编程的第一步。 ```python import threading ``` 2. 定义线程函数(target):你需要为每个线程定义一个函数,这个函数将在新线程中执行。 ```python def worker_function(arg): # 线程执行的代码 pass ``` 3. 创建线程对象:使用`Thread`类实例化一个线程,将定义的函数作为参数传递。 ```python thread = threading.Thread(target=worker_function, args=(arg,)) ``` 4. 启动线程:调用`start()`方法启动线程,此时线程会在后台运行。 ```python thread.start() ``` 5. 等待线程完成:如果你需要等待线程结束,可以使用`join()`方法。 ```python thread.join() # 如果你想让主线程等待这个线程结束 ``` 6. 错误处理:线程可能遇到异常,使用`threading`模块提供的异常处理器来捕获并处理。 ```python try: thread.start() except Exception as e: print(f"Error in thread: {e}") ``` 需要注意的是,Python中的全局解释器锁(GIL)限制了同一时间只能有一个线程在执行Python字节码。这意味着多线程并不能真正实现并行计算,但在IO密集型任务中仍然很有用,比如网络请求、文件读写等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值