----------------------android培训 java培训 期待与您交流! ----------------------
在实际实现线程时,Java 语言提供了三种实现方式:
1、 继承 Thread 类
2、 实现 Runnable 接口
3、 使用 Timer 和 TimerTask 组合
1、 继承 Thread 类
继承 Thread 类可以使该类具备多线程的能力,需要启动该线程时,只需要创建
该类的对象,然后调用该对象中的 start 方法。
例子:
public class Test {
public static void main(String[] args) {
//初始化线程
ThirdThread ft = new ThirdThread();
//启动线程
ft.start();
try{
for(int i = 0;i < 10;i++){
//延时 1 秒
Thread.sleep(1000);
System.out.println("main:" + i);
}
}catch(Exception e){}
}
}
public class ThirdThread extends Thread {
public void run(){
try{
for(int i = 0;i < 10;i++){
//延时 1 秒
Thread.sleep(1000);
System.out.println("run:" + i);
}
}catch(Exception e){}
}
}
2、 实现 Runnable 接口
在需要启动线程的地方,首先创建 MyRunnable 类型的对象,然后再以该对象为基础创建 Thread 类的对象,最后调用 Thread 对象的 start 方法即可启动线程。
代码如下:
//创建对象
MyRunnable mr = new MyRunnable();
Thread t = new Thread(mr);
//启动
t.start();
/** 使用实现 Runnable 接口的方式实现多线程 */
public class MyRunnable implements Runnable {
public void run() {
try{
for(int i = 0;i < 10;i++){
Thread.sleep(1000);
System.out.println("run:" + i);
}
}catch(Exception e){}
}
}
3、 使用 Timer 和 TimerTask 组合
Timer 类本身实现的就是一个线程,只是这个线程是用来实现调用其它线程的。
TimerTask 类是一个抽象类, 该类实现了 Runnable 接口,该类具备多线程的能力。
一个 Timer 启动的多个 TimerTask, 之间会存在影响,当上一个线程未执行完成时,会阻塞后续线程的执行。
启动线程时需要首先创建一个 Timer 类的对象,以及一个 MyTimerTask线程类的对象,然后使用 Timer 对象的 schedule 方法实现,启动线程的代码为:
//创建 Timer
Timer t = new Timer();
//创建 TimerTask
MyTimerTask mtt1 = new MyTimerTask("线程 1:");
//启动线程
t.schedule(mtt1, 0);
例子:
public class Test3 {
public static void main(String[] args) {
//创建 Timer
Timer t = new Timer();
//创建 TimerTask
MyTimerTask mtt1 = new MyTimerTask("线程 1:");
//启动线程
t.schedule(mtt1, 0);
}
}
import java.util.TimerTask;
/** 以继承 TimerTask 类的方式实现多线程 */
public class MyTimerTask extends TimerTask {
String s;
public MyTimerTask(String s){
this.s = s;
}
public void run() {
try{
for(int i = 0;i < 10;i++){
Thread.sleep(1000);
System.out.println(s + i);
}
}catch(Exception e){}
}
}
schedule 方法
A public void schedule(TimerTask task,Date time)
该方法的作用是在到达 time 指定的时间或已经超过该时间时执行线程 task。
代码:Date d = new Date(2009-1900,10-1,1,10,0,0);
t. schedule(task,d);
B public void schedule(TimerTask task, Date firstTime, long period)
该方法的作用是在时间到达 firstTime 开始,每隔 period 毫秒就启动一次 task 指定的 线程。
C public void schedule(TimerTask task,long delay)
该方法和第一个方法类似,作用是在执行 schedule 方法以后 delay 毫秒以后启动线程 task。
代码: t. schedule(task,1000);
该示例代码的作用是在执行该行启动代码 1000 毫秒以后启动一次线程 task。
D public void schedule(TimerTask task,long delay,long period)
该方法和第二个方法类似,作用是在执行 schedule 方法以后 delay 毫秒以后启动线程 task,然后每隔 period 毫秒重复启动线程 task。
----------------------android培训 java培训 期待与您交流! ----------------------