線程池newFixedThreadPool的使用

線程池newFixedThreadPool的使用,第1張

線程池newFixedThreadPool的使用,第2張

Examda提示:一個新線程加入後,如果正在運行的線程達到上限,就會阻塞,直到有空個空閑線程可以運行。
導入Java . util . random;
導入Java . util . concurrent . executorservice;
導入Java . util . concurrent . executors;
導入Java . util . concurrent . time unit;

public class executor test {
public static void main(String args[]){
Random Random = new Random();
//建立一個容量爲3的固定大小線程池
executorservice executor = executors . newfixedthreadpool(3);
//判斷線程池可以結束
int wait time = 500;
for(int I = 0;i < 10 ){
string name =" thread" I;
int time = random . nextint(1000);
wait time = time;
Runnable runner = new executor thread(name,time);
System.out.println("新增:" name"/" time);
executor . execute(runner);
}
嘗試{
thread . sleep(wait time);
executor . shut down();
executor . await termination(wait time,TimeUnit。毫秒);
} catch(interrupted exception忽略){
}
}
}
class executor thread實現Runnable {
private final String name;
私有最終int延遲;
public executor thread(String name,int delay){
this . name = name;
this . delay = delay;
}
public void run(){
system . out . println(" startup:" name);
試試{
Thread.sleep(延時);
} catch(忽略中斷異常){
}
system . out . println(" completed:" name);
}
}

位律師廻複

生活常識_百科知識_各類知識大全»線程池newFixedThreadPool的使用

0條評論

    發表評論

    提供最優質的資源集郃

    立即查看了解詳情