一、继承Thread类

Thread是一个实现了Runnable 接口的实例。

  1. public class ThreadDemo extends Thread {
  2. public void run(){
  3. System.out.println(" MyThread.run()");
  4. }
  5. public static void main(String args[]){
  6. ThreadDemo demo1 = new ThreadDemo();
  7. ThreadDemo demo2 = new ThreadDemo();
  8. Thread demo3 = new Thread(new RunnableDemo());
  9. demo1.start();
  10. demo2.start();
  11. demo3.start();
  12. }
  13. }

二、实现Runnable接口

实现接口后,需要重写Run方法。通过 new Thread(xxx) 方法获得实例化的 线程对象。

  1. public class RunnableDemo implements Runnable{
  2. public void run(){
  3. System.out.println(" Runnabl3 Demo");
  4. }
  5. }

三、Executor框架

ExectutorService、Callable、Future 类配合使用,可以创建有返回结果的多线程。

主类,构建线程池。

  1. import java.util.ArrayList;
  2. import java.util.concurrent.*;
  3. import java.util.List;
  4. public class FutureDemo {
  5. public static void main(String args[]) throws ExecutionException, InterruptedException {
  6. int taskSize = 5;
  7. ExecutorService pool = Executors.newFixedThreadPool(5);
  8. List<Future> futureList = new ArrayList();
  9. for(int i=0; i<taskSize; i++){
  10. Callable c = new RuntimeCallable(i);
  11. Future f = pool.submit(c);
  12. futureList.add(f);
  13. }
  14. pool.shutdown();
  15. for(Future f : futureList){
  16. System.out.println(f.get());
  17. }
  18. }
  19. }

继承Callable接口,得到线程执行类。 call方法是具体的执行逻辑。

  1. import java.util.concurrent.*;
  2. import java.util.Date;
  3. import java.util.Random;
  4. public class RuntimeCallable implements Callable<Object>{
  5. public String name;
  6. public RuntimeCallable(int i){
  7. this.name = "thread-"+i;
  8. }
  9. public Object call() throws Exception {
  10. Date start = new Date();
  11. Random random = new Random();
  12. Thread.sleep(random.nextInt(1000));
  13. Date end = new Date();
  14. return end.getTime() - start.getTime();
  15. }
  16. }