这几天,看了一下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