java 實現多線程的三種方法
在java中,有三種方法可以實現多線程。第一種方法:繼承Thread類,重寫run函數。第二種方法:實現Runnable接口,重寫run函數。第三種方法:實現Callable接口,重寫call函數。本文章將通過實例講解這三種方法如何實現多線程。需要的可以參考一下。
(1)繼承Thread類,重寫run函數。
class xx extends Thread{ public void run(){ Thread.sleep(1000) //線程休眠1000毫秒,sleep使線程進入Block狀態,并釋放資源 }}開啟線程:
對象.start() //啟動線程,run函數運行
(2)實現Runnable接口,代碼如下
class MyThread implements Runnable { private String name; public MyThread(String name) { super(); this.name = name; } @Override public void run() { for(int i = 0 ; i < 200; i++) { System.out.println("Thread"+name+"--->"+i); } }}public class ThreadDemo { public static void main(String[] args) { MyThread a = new MyThread("a"); MyThread b = new MyThread("b"); MyThread c = new MyThread("c"); new Thread(a).start(); new Thread(b).start(); new Thread(c).start(); }}(3)實現Callable接口,重寫call函數
Callable是類似于Runnable的接口,實現Callable接口的類和實現Runnable的類都是可被其它線程執行的任務。
Callable和Runnable有幾點不同:
Java Callable 代碼示例:
class TaskWithResult implements Callable<String> { private int id; public TaskWithResult(int id) { this.id = id; } @Override public String call() throws Exception { return "result of TaskWithResult " + id; }}public class CallableTest { public static void main(String[] args) throws InterruptedException, ExecutionException { ExecutorService exec = Executors.newCachedThreadPool(); ArrayList<Future<String>> results = new ArrayList<Future<String>>(); //Future 相當于是用來存放Executor執行的結果的一種容器 for (int i = 0; i < 10; i++) { results.add(exec.submit(new TaskWithResult(i))); } for (Future<String> fs : results) { if (fs.isDone()) { System.out.println(fs.get()); } else { System.out.println("Future result is not yet complete"); } } exec.shutdown(); }} 感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
新聞熱點
疑難解答