传统的实现线程的方式为三种,分别为继承Thread类,重写run()方法;实现Runable接口,重写run()方法;实现callable接口,重写call()方法;下面来记录一下最基本的三种编码实现。
一、继承Thread
public class ExtendsThread extends Thread{ public void run(){ System.out.println("Hello Thread"); } public static void main(String[] args) { ExtendsThread et1 = new ExtendsThread(); ExtendsThread et2 = new ExtendsThread(); et1.start(); et2.start(); } }
二、实现Runnable接口
public class ImplementsRunable implements Runnable { public void run() { System.out.println("Hello Thread"); } public static void main(String[] args) { ImplementsRunable ir1 = new ImplementsRunable(); ImplementsRunable ir2 = new ImplementsRunable(); new Thread(ir1).start(); new Thread(ir2).start(); } }
三、实现callable接口
public class ImplementsCallable implements Callable { private int id; public ImplementsCallable(int id){ this.id = id; } public String call() throws Exception { return "This Thread Id Is : "+this.getId(); } public int getId() { return id; } public void setId(int id) { this.id = id; } public static void main(String[] args) throws ExecutionException, InterruptedException { ExecutorService es = Executors.newCachedThreadPool(); List<Future<String>> results = new ArrayList(); for(int i=1;i<=10;i++){ results.add(es.submit(new ImplementsCallable(i))); } Thread.sleep(10000); for(Future<String> fs : results){ if (fs.isDone()) { System.out.println(fs.get()); } else { System.out.println("The Thread is not down yet"); } } es.shutdown(); } }
注:ExecutorService的execute()方法没有返回值,而submit()方法有返回值,类型为Future<T>。
时间: 2024-10-14 13:09:02