Java多執行緒的簡單實現以及耗時操作的效率對比

2021-08-02 04:10:09 字數 2835 閱讀 4753

public

class

threaddemo

}});

system.out.println("開始請求");

singlethread(command,executecount);

// multithread(command, executecount, 100);

}/**

* 單執行緒執行

**@param runnable run

*@param executecount 執行次數

*/public

static

void

singlethread(myrunnable runnable, int executecount)

}/**

* 多執行緒執行

**@param runnable run

*@param executecount 執行次數

*@param corethreadcount 核心執行緒數量

*/public

static

void

multithread(myrunnable runnable, int executecount, int corethreadcount)

}public

static

class

myrunnable

implements

runnable

thread.sleep(100);

system.out.println("執行緒:" + thread.currentthread().getname() + "第" + currentcount + "次請求完成");

} catch (interruptedexception e)

listener.end();

}public

void

setendlistener(endlistener listener)

inte***ce endlistener

}}

執行結果

singlethread(command,executecount);

開始請求

執行緒:pool-1-thread-1進行第0次請求

執行緒:pool-1-thread-1第0次請求完成

執行緒:pool-1-thread-1進行第1次請求

執行緒:pool-1-thread-1第1次請求完成

執行緒:pool-1-thread-1進行第2次請求

執行緒:pool-1-thread-1第2次請求完成

執行緒:pool-1-thread-1進行第3次請求

執行緒:pool-1-thread-1第3次請求完成

執行緒:pool-1-thread-1進行第4次請求

執行緒:pool-1-thread-1第4次請求完成

執行緒:pool-1-thread-1進行第5次請求

執行緒:pool-1-thread-1第5次請求完成

執行緒:pool-1-thread-1進行第6次請求

執行緒:pool-1-thread-1第6次請求完成

執行緒:pool-1-thread-1進行第7次請求

執行緒:pool-1-thread-1第7次請求完成

執行緒:pool-1-thread-1進行第8次請求

執行緒:pool-1-thread-1第8次請求完成

執行緒:pool-1-thread-1進行第9次請求

執行緒:pool-1-thread-1第9次請求完成

全部請求執行完畢,耗時:1132毫秒

multithread(command, executecount, 100);

開始請求

執行緒:pool-1-thread-1進行第0次請求

執行緒:pool-1-thread-2進行第1次請求

執行緒:pool-1-thread-3進行第2次請求

執行緒:pool-1-thread-4進行第3次請求

執行緒:pool-1-thread-5進行第4次請求

執行緒:pool-1-thread-6進行第5次請求

執行緒:pool-1-thread-7進行第6次請求

執行緒:pool-1-thread-8進行第7次請求

執行緒:pool-1-thread-9進行第8次請求

執行緒:pool-1-thread-10進行第9次請求

執行緒:pool-1-thread-1第0次請求完成

執行緒:pool-1-thread-2第1次請求完成

執行緒:pool-1-thread-3第2次請求完成

執行緒:pool-1-thread-5第4次請求完成

執行緒:pool-1-thread-6第5次請求完成

執行緒:pool-1-thread-4第3次請求完成

執行緒:pool-1-thread-7第6次請求完成

執行緒:pool-1-thread-10第9次請求完成

執行緒:pool-1-thread-9第8次請求完成

執行緒:pool-1-thread-8第7次請求完成

全部請求執行完畢,耗時:121毫秒

從以上執行的結果可知,當需要進行重複的耗時操作(比如網路請求),使用多執行緒能大大提高執行效率

附幾個常用的執行緒池方法:

executors.newcachedthreadpool()(無界線程池,可以進行自動線程**);

executors.newfixedthreadpool(int)(固定大小執行緒池);

executors.newsinglethreadexecutor()(單個後台執行緒);

java氣泡排序的實現以及優化

氣泡排序原理 1 比較相鄰的兩個元素,如果前者大於後者則交換位置 2 這樣對陣列第0個資料到n 1個資料進行遍歷比較一次後,最大的資料會移動到最後一位。3 n n 1,如果n 0則排序完成 實現 package zks public class bubblesort package zks publ...

Java 多執行緒實現

在實際應用中我們不會在乙個手機或者電腦上進行單執行緒的開發或者使用,一般都是多執行緒。執行緒 程式中執行的具體事務 程序 表示正在執行的應用程式,乙個程序可以有多個執行緒。事實上執行緒是有執行順序的,但是由於cpu執行的速度非常快,所以覺得是在併發執行,其實是偽裝的併發執行。執行緒的實現有兩種方法 ...

實現Java多執行緒

有三種使用執行緒的方法 class mythread extends thread public class test 推薦這個!實現這個介面的類還可以繼承自其它的類,用3.1就沒有辦法再去繼承別的類 step1 自定義類並實現rubbale介面,實現run 方法 step2 建立thread物件,...