C#Thread 线程的简单使用

来源:互联网 发布:足彩大数据 编辑:程序博客网 时间:2024/05/18 00:02
//*****************************************/// <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
原创粉丝点击