启动线程通过两种方式实现:
1、通过实现Runnable接口定义一个由Thread驱动的任务,后通过把自己传给Thread的构造来启动一个线程(Runnable没有返回值,如需返回值则使用Callable接口)。
@实现Runnable的一个任务
public class CountDown implements Runnable {
protected int count = 10 ;
public static int taskCount = 1 ;
public final int id = taskCount ++ ;
@Override
public void run() {
// TODO Auto-generated method stub
while (count -- > 0 )
{
System.out.println( "" + count);
}
System.out.println( " count over " );
Thread.yield();
}
}
@通过把任务传给Thread的构造来启动线程
2、直接继承自Thread来创建线程
@继承自Thread的线程
public class CountDown3 extends Thread {
private static int step = 0 ;
private final int id = step ++ ;
private int count = 10 ;
@Override
public void run() {
// TODO Auto-generated method stub
super .run();
while (count -- > 0 )
{
System.out.println(count);
Thread.yield();
}
}
}
@启动此线程
1、通过实现Runnable接口定义一个由Thread驱动的任务,后通过把自己传给Thread的构造来启动一个线程(Runnable没有返回值,如需返回值则使用Callable接口)。
@实现Runnable的一个任务
public class CountDown implements Runnable {
protected int count = 10 ;
public static int taskCount = 1 ;
public final int id = taskCount ++ ;
@Override
public void run() {
// TODO Auto-generated method stub
while (count -- > 0 )
{
System.out.println( "" + count);
}
System.out.println( " count over " );
Thread.yield();
}
}
@通过把任务传给Thread的构造来启动线程
public
class
MainThread {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Thread t = new Thread( new CountDown());
t.start();
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Thread t = new Thread( new CountDown());
t.start();
}
}
2、直接继承自Thread来创建线程
@继承自Thread的线程
public class CountDown3 extends Thread {
private static int step = 0 ;
private final int id = step ++ ;
private int count = 10 ;
@Override
public void run() {
// TODO Auto-generated method stub
super .run();
while (count -- > 0 )
{
System.out.println(count);
Thread.yield();
}
}
}
@启动此线程
public
class
MainThread {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Thread t = new CountDown3();
t.run();
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Thread t = new CountDown3();
t.run();
}
}