关于Java中Runnable和Thread的一些使用

 这几天,看了一下Java中的线程,觉得还是觉得有必要在线程这块儿说一说,因为这里的线程也牵涉到了安卓里的线程使用,好了,废话少说了,步入正题吧!
 大家都已知道Runnable只是个接口,里面就一个光秃秃的run方法,关于它,要记住一点,当从Runnable导出一个类时,这个类并无特殊之处,他不会产生内在的线程能力.要实现线程行为,你必须显式地将一个任务(其实我更愿意将Runnable导出的类称之为一个任务)附着在一个线程上(即Thread).
  看一下代码大家应该就清楚了,

public class LiftOff implements Runnable{
protected int countDown=10;
private static int taskcount=0;
private final int id=taskcount++;
public LiftOff()
{

}
public LiftOff(int ID)
{
    this.countDown=ID;
}
public String status()
{
    return "#"+id+"("+(countDown>0? countDown:"Liftoff!")+").";
}

@Override
public void run() {
    while(countDown-->0)
    {
        System.out.print(status());
        Thread.yield();
    }
    System.out.println("我是新的线程吗");
}
   public static void main(String[] args) {
       LiftOff l=new LiftOff();
       l.run();

    System.out.println("我是主线程");

}

}

这里是输出:

0(9).#0(8).#0(7).#0(6).#0(5).#0(4).#0(3).#0(2).#0(1).#0(Liftoff!).我是新的线程吗

我是主线程

可见不能仅用Runnable新建一个线程,这时若用到Thread,如下:

import java.util.concurrent.Executors;

public class LiftOff implements Runnable {
    protected int countDown = 10;
    private static int taskcount = 0;
    private final int id = taskcount++;

    public LiftOff() {
    }

    public LiftOff(int ID) {
        this.countDown = ID;
    }

    public String status() {
        return "#" + id + "(" + (countDown > 0 ? countDown : "Liftoff!") + ").";
    }

    @Override
    public void run() {
        while (countDown-- > 0) {
            System.out.print(status());
            Thread.yield();
        }
        System.out.println("我是新的线程吗");
    }

    public static void main(String[] args) {
        Thread t = new Thread(new LiftOff());
        t.start();
        System.out.println("我是主线程");

    }

}

输出:
我是主线程

0(9).#0(8).#0(7).#0(6).#0(5).#0(4).#0(3).#0(2).#0(1).#0(Liftoff!).我是新的线程吗

可见只有Thread类才能创建新的线程,独立于main线程,同时也可用Thread来驱动Runnable

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值