C#Thread 线程的简单使用

//*****************************************
/// <summary>
/// General method.2017.../cyl
/// </summary>
///*****************************************
using UnityEngine;
using System.Collections;
using System.Threading;
public class TestScriptThread : MonoBehaviour
{
    // Use this for initialization
    void Start ()
    {
//      Method1 ();
//      Method2 ();
//      Method3 ();
//      Method4();
        Method5 ();
    }
    //获取线程名字
    void Method1 ()
    {
        Thread th = Thread.CurrentThread;
        th.Name = "1号线";
        Debug.Log ("当前线程名字: " + th.Name);
    }
    //线程启动/创建
    void Method2 ()
    {
        ThreadStart childref = new ThreadStart (Method1);
        Debug.Log ("in main: createing the child thread!");
        Thread th = new Thread (childref);
        th.Start ();
        Debug.Log ("thread is start");
    }
    //线程开启和睡眠
    void Method3 ()
    {
        ThreadStart childref = new ThreadStart (Method3Event);
        Thread th = new Thread (childref);
        th.Start ();
    }
    void Method3Event ()
    {
        Debug.Log ("子线程开启");
        int sleepfor = 5000;
        Debug.Log ("子线程要睡眠" + (sleepfor / 1000) + "秒");
        Thread.Sleep (sleepfor);
        Debug.Log ("子线程重新挂起");
    }
    //线程销毁捕获异常
    void Method4 ()
    {
        ThreadStart childref = new ThreadStart (Method4Event);
        Thread th = new Thread (childref);
        th.Start ();
        Debug.Log ("线程暂停2秒");
        Thread.Sleep (2000);
        Debug.Log ("现在终止子线程");
        th.Abort ();
    }
    void Method4Event ()
    {
        try {
            Debug.Log ("子线程开启运行");
            for (int i = 0; i < 10; i++) {
                Thread.Sleep (500);
                Debug.Log ("当期下标 " + i.ToString ());
            }
            Debug.Log ("子线程运行完成!");
        } catch (System.Exception ex) {
            Debug.Log ("线程终止异常");
        } finally {
            Debug.Log ("没有抓找线程异常");
        }
    }
    void Method5 ()
    {
        //不带参数方法调用
        Thread t1 = new Thread (new ThreadStart (Method5Event));
        //带参数方法调用
        Thread t2 = new Thread (new ParameterizedThreadStart (Method5Event));
        t1.IsBackground = true;
        t2.IsBackground = true;
        t1.Start ();
        t2.Start ("hello world!");
    }
    void Method5Event()
    {
        Debug.Log ("不带参数的线程函数");
    }
    void Method5Event(object data)
    {
        string datastr = (string)data;
        Debug.Log ("带参数的线程,参数为: " + datastr);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值