一、继承Thread类
Thread是一个实现了Runnable 接口的实例。
public class ThreadDemo extends Thread {
public void run(){
System.out.println(" MyThread.run()");
}
public static void main(String args[]){
ThreadDemo demo1 = new ThreadDemo();
ThreadDemo demo2 = new ThreadDemo();
Thread demo3 = new Thread(new RunnableDemo());
demo1.start();
demo2.start();
demo3.start();
}
}
二、实现Runnable接口
实现接口后,需要重写Run方法。通过 new Thread(xxx) 方法获得实例化的 线程对象。
public class RunnableDemo implements Runnable{
public void run(){
System.out.println(" Runnabl3 Demo");
}
}
三、Executor框架
ExectutorService、Callable、Future 类配合使用,可以创建有返回结果的多线程。
主类,构建线程池。
import java.util.ArrayList;
import java.util.concurrent.*;
import java.util.List;
public class FutureDemo {
public static void main(String args[]) throws ExecutionException, InterruptedException {
int taskSize = 5;
ExecutorService pool = Executors.newFixedThreadPool(5);
List<Future> futureList = new ArrayList();
for(int i=0; i<taskSize; i++){
Callable c = new RuntimeCallable(i);
Future f = pool.submit(c);
futureList.add(f);
}
pool.shutdown();
for(Future f : futureList){
System.out.println(f.get());
}
}
}
继承Callable接口,得到线程执行类。 call方法是具体的执行逻辑。
import java.util.concurrent.*;
import java.util.Date;
import java.util.Random;
public class RuntimeCallable implements Callable<Object>{
public String name;
public RuntimeCallable(int i){
this.name = "thread-"+i;
}
public Object call() throws Exception {
Date start = new Date();
Random random = new Random();
Thread.sleep(random.nextInt(1000));
Date end = new Date();
return end.getTime() - start.getTime();
}
}