线程的使用

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
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值