1)Thread:java
public class ThreadTest extends Thread { public void run(){ System.out.println(Thread.currentThread()+"say : hello"); } public static void main(String[] args){ new ThreadTest().start(); new ThreadTest().start(); new ThreadTest().start(); new ThreadTest().start(); new ThreadTest().start(); } }
執行結果:異步
Thread[Thread-2,5,main]say : hello
Thread[Thread-4,5,main]say : hello
Thread[Thread-3,5,main]say : hello
Thread[Thread-0,5,main]say : hello
Thread[Thread-1,5,main]say : hello線程
2)Runnable:code
public class RunnableTest implements Runnable{ public void run() { System.out.println(Thread.currentThread()+"say: hello"); } public static void main(String[] args){ RunnableTest rt = new RunnableTest(); new Thread(rt,"111").start(); new Thread(rt,"222").start(); new Thread(rt,"333").start(); new Thread(rt).start(); new Thread(rt).start(); } }
執行結果:接口
Thread[111,5,main]say: hello
Thread[333,5,main]say: hello
Thread[Thread-0,5,main]say: hello
Thread[222,5,main]say: hello
Thread[Thread-1,5,main]say: hello字符串
3)Callable:get
public class CallableTest implements Callable<String>{//Callable<V>是泛型,不必定爲String類型 public String call() throws Exception { System.out.println(Thread.currentThread()+" say : hello"); return "返回字符串:"+Thread.currentThread().toString(); } public static void main(String[] args){ //Callable和Future一個產生結果,一個拿到結果。 //Callable接口相似於Runnable,可是Runnable不會返回結果, //而Callable能夠返回結果,這個返回值能夠被Future拿到, //也就是說,Future能夠拿到異步執行任務的返回值。 CallableTest ct = new CallableTest();//至關於Callable執行call()內容 CallableTest ct2 = new CallableTest(); FutureTask<String> ft = new FutureTask<>(ct);//至關於Futrue計算Callable返回的結果 FutureTask<String> ft2 = new FutureTask<>(ct2); new Thread(ft,"有返回值得線程").start(); new Thread(ft2).start(); try { //callable的返回值 System.out.println(ft.get()); System.out.println(ft2.get()); } catch (Exception e) { e.printStackTrace(); } } }
執行結果:io
Thread[Thread-0,5,main] say : hello
Thread[有返回值得線程,5,main] say : hello
返回字符串:Thread[有返回值得線程,5,main]
返回字符串:Thread[Thread-0,5,main]class