线程操作范例

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启动线程
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值