一、编写一个类,直接继承java.lang.Thread,重写run方法。
class MyThread extends Thread{
@Override
public void run() {
// 编写程序,这段程序运行在分支线程中(分支栈)。
}
}
// 创建线程对象
MyThread t = new MyThread();
// 启动线程
t.start();
二、编写一个类,实现java.lang.Runnable接口,实现run方法。
class MyRunnable implements Runnable{
@Override
public void run() {
}
}
// 创建线程对象
Thread t = new Thread(new MyRunnable());
// 启动线程
t.start();
三、 编写一个类,实现java.lang.Runnable接口,实现run方法,采用内部类的方式。
Thread t = new Thread(new Runnable() {
@Override
public void run() {
}
});
// 启动线程
t.start();
四、 编写一个类,实现java.util.concurrent.Callable接口,实现call方法,获取一个线程的执行结果。
package java.thread;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask; 新特性。
/*
实现线程的第三种方式:
实现Callable接口
这种方式的优点:可以获取到线程的执行结果。
这种方式的缺点:效率比较低,在获取t线程执行结果的时候,当前线程受阻塞,效率较低。
*/
public class ThreadTest15 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureTask task = new FutureTask(new Callable() {
@Override
public Object call() throws Exception {
System.out.println("call method begin");
Thread.sleep(1000 * 10);
System.out.println("call method over");
int a = 100;
int b = 100;
return a + b; // 自动装箱(200结果变成Integer)
}
});
// 创建线程对象
Thread t = new Thread(task);
// 启动线程
t.start();
Object obj = task.get();
System.out.println("线程执行结果:" + obj);
System.out.println("hello world!");
}
}