三种多线程使用框架
1 Thread类使用框架
public class MyThread extends Thread{
public void run() {}
}
public static void main(String[] args) {
Thread threadA = new MyThread();
Thread threadB = new MyThread();
threadA.start();
threadB.start();
//或new Thread(new MyThread()).start();
}
2 Runnable类使用框架(解决Thread类无法多继承问题)
public class MyThread implements Runnable{
public void run() { }
}
public static void main(String[] args) {
MyThread mt = new MyThread();
new Thread(mt).start();
new Thread(mt).start();
}
一层包裹,先实例化MyThread再用Thread包裹 Thread.start()启动多线程
3 Callable类使用框架(解决Thread无返回值问题)
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
class MyThread implements Callable<String>{
public String call() { } //有返回值
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
MyThread mt = new MyThread();
FutureTask<String> taskA = new FutureTask<String>(mt);
FutureTask<String> taskB = new FutureTask<String>(mt);
new Thread(taskA, "线程A").start();
new Thread(taskB, "线程B").start();
System.out.println(taskA.get()); //获取返回值
System.out.println(taskB.get());
}
两层包裹,先实例化MyThread用FutureTask<泛型>类包裹,再用Thread包裹 Thread.start()启动多线程
|