(40)多執行緒 實現多執行緒方法

2021-09-25 18:14:03 字數 1002 閱讀 5348

/**

* 建立執行緒用法:

* 1.繼承thread,重寫run()方法,

* 建立子類物件  :a a = new a(); 

* 執行緒開始執行  : a.start();

* * 2.實現runnable介面,實現run()方法,

* 《建立實現類物件   :  a a = new a(); 

* 建立**類物件   :  thread t = new thread(a);

* 執行緒開始執行       : t.start();

* 上面步驟可以簡化寫成:

* new thread(new a).start();

* 相比於第乙個方法,更推薦使用第二個方法:

* 原因:

* ①避免但繼承的侷限性,優先使用介面 

* ②方便資源共享

* * 3.實現callable介面

* <1.建立目標物件:c********** cd = new c**********("位址","baidu.com");

* <2.建立執行服務:executorservice ser = executors.newfixedthreadpool(2);//2表示有兩個執行緒

* <3.提交執行:futureresult1 = ser.submit(cd);

* <4.獲取結果:boolean r1 = result1.get();

* <5.關閉服務:ser.shutdownnow(); 

* 《可以拋異常,可以有返回值

* * 4.執行緒池

*/第一種:繼承thread,重寫run();方法

執行結果:

實現多執行緒的方法

import threading import time import thread def job print 這是乙個需要執行的任務。print 當前執行緒的個數 threading.active count print 當前執行緒的資訊 threading.current thread tim...

執行緒基礎 實現多執行緒

public class thread01 extends thread public static void main string args public class thread02 implements runnable public static void main string args...

多執行緒 多執行緒原理

我們首先要知道什麼是多執行緒,說白了就是多個執行緒,執行緒是什麼呢,其實就是程序執行的途徑,那麼說道這裡我們又引入了乙個新的名字,就是程序,那麼我們來看看什麼是程序,其實我們自己也能看到,啟動電腦的任務管理器,我們就可以看到程序選項,裡面是我們電腦所有的程序,我們會發現有很多的程序.簡單地說就是程序...