Java中建立線程有三種,分別爲實現Runnable接口,繼承Thread類,實現Callable接口。java
1.Threadide
public class MyThread extends Thread { public MyThread() { this.setName("MyThread"); } public void run() { while(true){ System.out.println("當前運行的線程: "+this.getName()); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } public static void main(String []args){ new MyThread().start(); } }
2.Runnable接口this
public class RunnableTask implements Runnable { @Override public void run() { // TODO Auto-generated method stub while (true) { System.out.println("當前運行的線程: " + Thread.currentThread().getName()); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public static void main(String[] args) throws InterruptedException { RunnableTask task = new RunnableTask(); new Thread(task).start(); new Thread(task).start(); } }
以上兩種方式沒有返回值。線程
3.Callable接口code
public class CallableTest { public static void main(String []args) throws Exception { Callable<Integer> call = new Callable<Integer>() { @Override public Integer call() throws Exception { System.out.println("thread start.."); Thread.sleep(2000); return 1; } }; FutureTask<Integer> task = new FutureTask<>(call); Thread t = new Thread(task); t.start(); System.out.println("do other thing.."); System.out.println("拿到線程的執行結果 : " + task.get()); } }
控制檯輸出:繼承
do other thing.. thread start.. 拿到線程的執行結果 : 1
Callable和Runnable的區別:接口