线程操作范例

1.1 使用 Thread 类

在Thread中直接存在了name属性,

class MyThread extends Thread
{
    public int time ;       //设置时间属性
    public MyThread(String name,int time) //Thread类中有name属性
    {
        super(name) ;       //为name属性赋值
        this.time = time ;  //设置休眠时间
    }
    public void run()       //覆写run()方法
    {
        try
        {
            Thread.sleep(this.time) ;//休眠指定的时间
        }
        catch (InterruptedException e)
        {
            e.printStackTrace() ;
        }
        System.out.println(Thread.currentThread().getName()
                           +"线程,休眠"+this.time+"毫秒") ;
    }
}
public class ExecDemo01
{
    public static void main(String[] args)
    {
        MyThread mt1 = new MyThread("线程A",2000) ;
        MyThread mt2 = new MyThread("线程B",3000) ;
        mt1.start() ;       //启动线程
        mt2.start() ;       //启动线程
    }
}

1.2 使用Runnable接口
如果使用Runnable接口,则类中是不存在线程名称的,需要单独创建一个name属性,以保存线程名称。
而且启动线程的时候 使用 new Thread(类对象).start()

class MyThread implements Runnable
{   
    public String name ;    //接口中没有name属性,需要建立一个 以保存线程名称
    public int time ;       //设置时间属性
    public MyThread(String name,int time) //Thread类中有name属性
    {
        this.name = name  ;     //为name属性赋值
        this.time = time ;  //设置休眠时间
    }
    public void run()       //覆写run()方法
    {
        try
        {
            Thread.sleep(this.time) ;//休眠指定的时间
        }
        catch (InterruptedException e)
        {
            e.printStackTrace() ;
        }
        System.out.println(this.name+"线程,休眠"+this.time+"毫秒") ;
    }
}
public class ExecDemo01
{
    public static void main(String[] args)
    {
        MyThread mt1 = new MyThread("线程A",2000) ;
        MyThread mt2 = new MyThread("线程B",3000) ;
        new Thread(mt1).start() ;   //new Thread(类对象).start()
        new Thread(mt2).start() ;   //n启动线程
    }
}
以下是一个简单的Unity3D中多线程交互的范例,使用C#的线程(Thread)来进行操作: ```csharp using UnityEngine; using System.Threading; public class ThreadExample : MonoBehaviour { private bool isRunning = false; private void Start() { // 创建并启动线程 Thread thread = new Thread(CountNumbers); thread.Start(); isRunning = true; } private void Update() { if (isRunning) { // 在主线程中更新UI或执行其他操作 Debug.Log("Main thread is running"); } } private void CountNumbers() { for (int i = 0; i < 10; i++) { Debug.Log("Count: " + i); Thread.Sleep(1000); // 模拟耗时操作 } isRunning = false; } } ``` 在上面的范例中,我们创建了一个简单的计数器,使用线程在后台进行计数,并在主线程中更新UI。在Start方法中,我们创建了一个新的线程,并调用CountNumbers方法开始计数。在CountNumbers方法中,我们使用Thread.Sleep方法来模拟耗时操作。 在Update方法中,我们检查isRunning变量的状态,如果为true,则表示计数仍在进行中,可以在主线程中执行其他操作。 需要注意的是,Unity的主要API(如渲染和更新)是在主线程中执行的,因此如果需要在其他线程中执行某些逻辑并与主线程进行交互,需要使用MainThreadDispatcher或其他线程同步机制来确保操作的正确执行。 这只是一个简单的示例,实际应用中可能需要更复杂的线程交互逻辑和数据同步机制,具体实现方式取决于您的需求。在使用多线程时,还需要注意线程安全和资源管理等问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值