欧美一区二区三区老妇人-欧美做爰猛烈大尺度电-99久久夜色精品国产亚洲a-亚洲福利视频一区二区

java開啟線程代碼 java開啟線程的方式

java啟用另外一個線程設(shè)置無超時狀態(tài)

Java的線程是不允許啟動兩次的,第二次調(diào)用必然會拋出IllegalThreadStateException,這是一種運(yùn)行時異常,多次調(diào)用start被認(rèn)為是編程錯誤。

十多年的興文網(wǎng)站建設(shè)經(jīng)驗(yàn),針對設(shè)計、前端、開發(fā)、售后、文案、推廣等六對一服務(wù),響應(yīng)快,48小時及時工作處理。全網(wǎng)營銷推廣的優(yōu)勢是能夠根據(jù)用戶設(shè)備顯示端的尺寸不同,自動調(diào)整興文建站的顯示方式,使網(wǎng)站能夠適用不同顯示終端,在瀏覽器中調(diào)整網(wǎng)站的寬度,無論在任何一種瀏覽器上瀏覽網(wǎng)站,都能展現(xiàn)優(yōu)雅布局與設(shè)計,從而大程度地提升瀏覽體驗(yàn)。創(chuàng)新互聯(lián)公司從事“興文網(wǎng)站設(shè)計”,“興文網(wǎng)站推廣”以來,每個客戶項(xiàng)目都認(rèn)真落實(shí)執(zhí)行。

關(guān)于線程生命周期的不同狀態(tài),在Java 5以后,線程狀態(tài)被明確定義在其公共內(nèi)部枚舉類型java.lang.Thread.State中,分別是:

新建(NEW),表示線程被創(chuàng)建出來還沒真正啟動的狀態(tài),可以認(rèn)為它是個Java內(nèi)部狀態(tài)。

就緒(RUNNABLE),表示該線程已經(jīng)在JVM中執(zhí)行,當(dāng)然由于執(zhí)行需要計算資源,它可能是正在運(yùn)行,也可能還在等待系統(tǒng)分配給它CPU片段,在就緒隊列里面排隊。 在其他一些分析中,會額外區(qū)分一種狀態(tài)RUNNING,但是從Java API的角度,并不能表示出來。

阻塞(BLOCKED),這個狀態(tài)和我們前面兩講介紹的同步非常相關(guān),阻塞表示線程在等待Monitor lock。比如,線程試圖通過synchronized去獲取某個鎖,但是其他線程已經(jīng)獨(dú)占了,那么當(dāng)前線程就會處于阻塞狀態(tài)。

等待(WAITING),表示正在等待其他線程采取某些操作。一個常見的場景是類似生產(chǎn)者消費(fèi)者模式,發(fā)現(xiàn)任務(wù)條件尚未滿足,就讓當(dāng)前消費(fèi)者線程等待(wait),另外的生產(chǎn)者線程去準(zhǔn)備任務(wù)數(shù)據(jù),然后通過類似notify等動作,通知消費(fèi)線程可以繼續(xù)工作了。Thread.join()也會令線程進(jìn)入等待狀態(tài)。

計時等待(TIMED_WAIT),其進(jìn)入條件和等待狀態(tài)類似,但是調(diào)用的是存在超時條件的方法,比如wait或join等方法的指定超時版本,如下面示例:

public final native void wait(long timeout) throws InterruptedException;

終止(TERMINATED),不管是意外退出還是正常執(zhí)行結(jié)束,線程已經(jīng)完成使命,終止運(yùn)行,也有人把這個狀態(tài)叫作死亡。

在第二次調(diào)用start()方法的時候,線程可能處于終止或者其他(非NEW)狀態(tài),但是不論如何,都是不可以再次啟動的。

考點(diǎn)分析

今天的問題可以算是個常見的面試熱身題目,前面的給出的典型回答,算是對基本狀態(tài)和簡單流轉(zhuǎn)的一個介紹,如果覺得還不夠直觀,我在下面分析會對比一個狀態(tài)圖進(jìn)行介紹??偟膩碚f,理解線程對于我們?nèi)粘i_發(fā)或者診斷分析,都是不可或缺的基礎(chǔ)。

面試官可能會以此為契機(jī),從各種不同角度考察你對線程的掌握:

相對理論一些的面試官可以會問你線程到底是什么以及Java底層實(shí)現(xiàn)方式。

線程狀態(tài)的切換,以及和鎖等并發(fā)工具類的互動。

線程編程時容易踩的坑與建議等。

可以看出,僅僅是一個線程,就有非常多的內(nèi)容需要掌握。我們選擇重點(diǎn)內(nèi)容,開始進(jìn)入詳細(xì)分析。

知識擴(kuò)展

首先,我們來整體看一下線程是什么?

從操作系統(tǒng)的角度,可以簡單認(rèn)為,線程是系統(tǒng)調(diào)度的最小單元,一個進(jìn)程可以包含多個線程,作為任務(wù)的真正運(yùn)作者,有自己的棧(Stack)、寄存器(Register)、本地存儲(Thread Local)等,但是會和進(jìn)程內(nèi)其他線程共享文件描述符、虛擬地址空間等。

在具體實(shí)現(xiàn)中,線程還分為內(nèi)核線程、用戶線程,Java的線程實(shí)現(xiàn)其實(shí)是與虛擬機(jī)相關(guān)的。對于我們最熟悉的Sun/Oracle JDK,其線程也經(jīng)歷了一個演進(jìn)過程,基本上在Java 1.2之后,JDK已經(jīng)拋棄了所謂的Green Thread,也就是用戶調(diào)度的線程,現(xiàn)在的模型是一對一映射到操作系統(tǒng)內(nèi)核線程。

如果我們來看Thread的源碼,你會發(fā)現(xiàn)其基本操作邏輯大都是以JNI形式調(diào)用的本地代碼。

典型Java線程池的代碼及其各部分功能介紹

( )根據(jù)xml文件來管理線程池的最大最小線程數(shù)( )對線程池通過Timer定期掃描以防止線程未激活 ( )通過某一個變量(本程序中是freeThreadCount)來得到空閑線程的數(shù)目 一 配置xml(listen xml)是 ?xml version= encoding= UTF ?configConsumeThreadPoolminPools /minPools ! 線程池最小線程 maxPools /maxPools! 線程池最大線程 checkThreadPeriod /checkThreadPeriod ! 檢查線程池中線程的周期 分鐘 /ConsumeThreadPool/config 二 對于ConsumeThreadPoolPara的javabean: import java io *;public class ConsumeThreadPoolPara implements Serializable{private int minPools;private int maxPools;private int checkThreadPeriod;public int getMinPools(){return minPools;}public int getMaxPools(){return maxPools;}public int getCheckThreadPeriod(){return checkThreadPeriod;}public void setMinPools(int minPools){this minPools = minPools;}public void setMaxPools(int maxPools){this maxPools = maxPools;}public void setCheckThreadPeriod(int checkThreadPeriod){this checkThreadPeriod = checkThreadPeriod;}public String toString(){return minPools+ + maxPools+ +checkThreadPeriod;}public ConsumeThreadPoolPara() {}public static void main(String[] args) {ConsumeThreadPoolPara consumeThreadPool = new ConsumeThreadPoolPara();}} 三 解析xml程序代碼(生成ConsumeThreadPoolPara) 使用jdom解析 import jdom *;import jdom input SAXBuilder;import java io *;import java util *;public class ParseConfig {static Hashtable Listens = null;static ConnPara connpara = null;static ConsumeThreadPoolPara consumeThreadPoolPara = null;private static String configxml = listen xml ;static{getConsumeThreadPoolPara(); //得到消費(fèi)的線程池的參數(shù)}/*** 裝載文檔* @return 返回根結(jié)點(diǎn)* @throws JDOMException*/public static Element loadDocument() throws JDOMException{SAXBuilder parser = new SAXBuilder(); // 新建立構(gòu)造器try {Document document = parser build(configxml);Element root = document getRootElement();return root;}catch(JDOMException e){logger error( listen xml文件格式非法! );throw new JDOMException();}}public static ConsumeThreadPoolPara getConsumeThreadPoolPara(){if(consumeThreadPoolPara ==null){try {Element root = loadDocument();Element consumeThreadPool = root getChild( ConsumeThreadPool );if (consumeThreadPool != null) { //代表有數(shù)據(jù)庫配置consumeThreadPoolPara = new ConsumeThreadPoolPara();Element minPools = consumeThreadPool getChild( minPools );consumeThreadPoolPara setMinPools(Integer parseInt(minPools getTextTrim()));Element maxPools = consumeThreadPool getChild( maxPools );consumeThreadPoolPara setMaxPools(Integer parseInt(maxPools getTextTrim()));Element checkThreadPeriod = consumeThreadPool getChild( checkThreadPeriod );consumeThreadPoolPara setCheckThreadPeriod(Integer parseInt(checkThreadPeriod getTextTrim()));}}catch (JDOMException e) {}}return consumeThreadPoolPara;}} 四 線程池源代碼 import java util *;/*** pTitle: 線程池/p* pDescription: 采集消費(fèi)模塊/p* pCopyright: Copyright (c) /p* pCompany: /p* @author 張榮斌* @version */public class ThreadPool {private static int minPools = ; //最小連接池數(shù)目private static int maxPools = ; //最大連接池數(shù)目private static int checkThreadPeriod = ; //檢查連接池的周期ArrayList m_ThreadList; //工作線程列表LinkedList m_RunList = null; //工作任務(wù)列表int totalThread = ; //總線程數(shù)static int freeThreadCount = ; //未被使用的線程數(shù)目private java util Timer timer = null; //定時器static Object o = new Object();static{ //先初始化線程池的參數(shù)ConsumeThreadPoolPara consumeThreadPoolPara = ParseConfig getConsumeThreadPoolPara();if(consumeThreadPoolPara!=null){minPools = consumeThreadPoolPara getMinPools();maxPools = consumeThreadPoolPara getMaxPools();checkThreadPeriod = consumeThreadPoolPara getCheckThreadPeriod()* * ;}}public void setMinPools(int minPools){this minPools = minPools;}public void setMaxPools(int maxPools){this maxPools = maxPools;}public void setCheckThreadPeriod(int checkThreadPeriod){this checkThreadPeriod = checkThreadPeriod;}public ThreadPool() {m_ThreadList=new ArrayList();m_RunList=new LinkedList();for(int i= ;iminPools;i++){WorkerThread temp=new WorkerThread();totalThread = totalThread + ;m_ThreadList add(temp);temp start();try{Thread sleep( );}catch(Exception e){}}timer = new Timer(true); //啟動定時器timer schedule(new CheckThreadTask(this) checkThreadPeriod);}/*** 當(dāng)有一個工作來的時候啟動線程池的線程* 當(dāng)空閑線程數(shù)為 的時候 看總線程是否小于最大線程池的數(shù)目 就new一個新的線程 否則sleep 直到有空閑線程為止;* 當(dāng)空閑線程不為 則將任務(wù)丟給空閑線程去完成* @param work*/public synchronized void run(String work){if (freeThreadCount == ) {if(totalThreadmaxPools){WorkerThread temp = new WorkerThread();totalThread = totalThread + ;m_ThreadList add(temp);temp start();synchronized(m_RunList){m_RunList add(work);m_RunList notify();}}else{while (freeThreadCount == ) {try {Thread sleep( );}catch (InterruptedException e) {}}synchronized(m_RunList){m_RunList add(work);m_RunList notify();}}} else {synchronized(m_RunList){m_RunList add(work);m_RunList notify();}}}/*** 檢查所有的線程的有效性*/public synchronized void checkAllThreads() {Iterator lThreadIterator = erator();while (lThreadIterator hasNext()) { //逐個遍厲WorkerThread lTestThread = (WorkerThread) lThreadIterator next();if (! (lTestThread isAlive())) { //如果處在非活動狀態(tài)時lTestThread = new WorkerThread(); //重新生成個線程lTestThread start(); //啟動}}}/*** 打印調(diào)試信息*/public void printDebugInfo(){System out println( totalThread= +totalThread);System out println( m_ThreadList size()= +m_ThreadList size());}/**** pTitle: 工作線程類/p* @author 張榮斌* @version */class WorkerThread extends Thread{boolean running = true;String work;public void run(){while(running){synchronized(o){freeThreadCount++;}synchronized(m_RunList){while(m_RunList size() == ){try{m_RunList wait();if(!running) return;}catch(InterruptedException e){} lishixinzhi/Article/program/Java/gj/201311/27379

Java實(shí)現(xiàn)通用線程池

線程池通俗的描述就是預(yù)先創(chuàng)建若干空閑線程 等到需要用多線程去處理事務(wù)的時候去喚醒某些空閑線程執(zhí)行處理任務(wù) 這樣就省去了頻繁創(chuàng)建線程的時間 因?yàn)轭l 繁創(chuàng)建線程是要耗費(fèi)大量的CPU資源的 如果一個應(yīng)用程序需要頻繁地處理大量并發(fā)事務(wù) 不斷的創(chuàng)建銷毀線程往往會大大地降低系統(tǒng)的效率 這時候線程池就派 上用場了

本文旨在使用Java語言編寫一個通用的線程池 當(dāng)需要使用線程池處理事務(wù)時 只需按照指定規(guī)范封裝好事務(wù)處理對象 然后用已有的線程池對象去自動選擇空 閑線程自動調(diào)用事務(wù)處理對象即可 并實(shí)現(xiàn)線程池的動態(tài)修改(修改當(dāng)前線程數(shù) 最大線程數(shù)等) 下面是實(shí)現(xiàn)代碼

//ThreadTask java

package polarman threadpool;

/** *//**

*線程任務(wù)

* @author ryang

*

*/

public interface ThreadTask {

public void run();

}

//PooledThread java

package polarman threadpool;

import java util Collection; import java util Vector;

/** *//**

*接受線程池管理的線程

* @author ryang

*

*/

public class PooledThread extends Thread {

protected Vector tasks = new Vector();

protected boolean running = false;

protected boolean stopped = false;

protected boolean paused = false;

protected boolean killed = false;

private ThreadPool pool;

public PooledThread(ThreadPool pool) { this pool = pool;

}

public void putTask(ThreadTask task) { tasks add(task);

}

public void putTasks(ThreadTask[] tasks) { for(int i= ; itasks length; i++) this tasks add(tasks[i]);

}

public void putTasks(Collection tasks) { this tasks addAll(tasks);

}

protected ThreadTask popTask() { if(tasks size() ) return (ThreadTask)tasks remove( );

else

return null;

}

public boolean isRunning() {

return running;

}

public void stopTasks() {

stopped = true;

}

public void stopTasksSync() {

stopTasks();

while(isRunning()) { try {

sleep( );

} catch (InterruptedException e) {

}

}

}

public void pauseTasks() {

paused = true;

}

public void pauseTasksSync() {

pauseTasks();

while(isRunning()) { try {

sleep( );

} catch (InterruptedException e) {

}

}

}

public void kill() { if(!running)

interrupt();

else

killed = true;

}

public void killSync() {

kill();

while(isAlive()) { try {

sleep( );

} catch (InterruptedException e) {

}

}

}

public synchronized void startTasks() {

running = true;

this notify();

}

public synchronized void run() { try { while(true) { if(!running || tasks size() == ) { pool notifyForIdleThread(); //System out println(Thread currentThread() getId() + : 空閑 ); this wait(); }else {

ThreadTask task;

while((task = popTask()) != null) { task run(); if(stopped) {

stopped = false;

if(tasks size() ) { tasks clear(); System out println(Thread currentThread() getId() + : Tasks are stopped );

break;

}

}

if(paused) {

paused = false;

if(tasks size() ) { System out println(Thread currentThread() getId() + : Tasks are paused );

break;

}

}

}

running = false;

}

if(killed) {

killed = false;

break;

}

}

}catch(InterruptedException e) {

return;

}

//System out println(Thread currentThread() getId() + : Killed );

}

}

//ThreadPool java

package polarman threadpool;

import java util Collection; import java util Iterator; import java util Vector;

/** *//**

*線程池

* @author ryang

*

*/

public class ThreadPool {

protected int maxPoolSize;

protected int initPoolSize;

protected Vector threads = new Vector();

protected boolean initialized = false;

protected boolean hasIdleThread = false;

public ThreadPool(int maxPoolSize int initPoolSize) { this maxPoolSize = maxPoolSize; this initPoolSize = initPoolSize;

}

public void init() {

initialized = true;

for(int i= ; iinitPoolSize; i++) {

PooledThread thread = new PooledThread(this);

thread start(); threads add(thread);

}

//System out println( 線程池初始化結(jié)束 線程數(shù)= + threads size() + 最大線程數(shù)= + maxPoolSize);

}

public void setMaxPoolSize(int maxPoolSize) { //System out println( 重設(shè)最大線程數(shù) 最大線程數(shù)= + maxPoolSize); this maxPoolSize = maxPoolSize;

if(maxPoolSize getPoolSize())

setPoolSize(maxPoolSize);

}

/** *//**

*重設(shè)當(dāng)前線程數(shù)

* 若需殺掉某線程 線程不會立刻殺掉 而會等到線程中的事務(wù)處理完成* 但此方法會立刻從線程池中移除該線程 不會等待事務(wù)處理結(jié)束

* @param size

*/

public void setPoolSize(int size) { if(!initialized) {

initPoolSize = size;

return;

}else if(size getPoolSize()) { for(int i=getPoolSize(); isize imaxPoolSize; i++) {

PooledThread thread = new PooledThread(this);

thread start(); threads add(thread);

}

}else if(size getPoolSize()) { while(getPoolSize() size) { PooledThread th = (PooledThread)threads remove( ); th kill();

}

}

//System out println( 重設(shè)線程數(shù) 線程數(shù)= + threads size());

}

public int getPoolSize() { return threads size();

}

protected void notifyForIdleThread() {

hasIdleThread = true;

}

protected boolean waitForIdleThread() {

hasIdleThread = false;

while(!hasIdleThread getPoolSize() = maxPoolSize) { try { Thread sleep( ); } catch (InterruptedException e) {

return false;

}

}

return true;

}

public synchronized PooledThread getIdleThread() { while(true) { for(Iterator itr=erator(); itr hasNext();) { PooledThread th = (PooledThread)itr next(); if(!th isRunning())

return th;

}

if(getPoolSize() maxPoolSize) {

PooledThread thread = new PooledThread(this);

thread start(); threads add(thread);

return thread;

}

//System out println( 線程池已滿 等待 );

if(waitForIdleThread() == false)

return null;

}

}

public void processTask(ThreadTask task) {

PooledThread th = getIdleThread();

if(th != null) { th putTask(task); th startTasks();

}

}

public void processTasksInSingleThread(ThreadTask[] tasks) {

PooledThread th = getIdleThread();

if(th != null) { th putTasks(tasks); th startTasks();

}

}

public void processTasksInSingleThread(Collection tasks) {

PooledThread th = getIdleThread();

if(th != null) { th putTasks(tasks); th startTasks();

}

}

}

下面是線程池的測試程序

//ThreadPoolTest java

import java io BufferedReader; import java io IOException; import java io InputStreamReader;

import polarman threadpool ThreadPool; import polarman threadpool ThreadTask;

public class ThreadPoolTest {

public static void main(String[] args) { System out println( quit 退出 ); System out println( task A 啟動任務(wù)A 時長為 秒 ); System out println( size 設(shè)置當(dāng)前線程池大小為 ); System out println( max 設(shè)置線程池最大線程數(shù)為 ); System out println();

final ThreadPool pool = new ThreadPool( ); pool init();

Thread cmdThread = new Thread() { public void run() {

BufferedReader reader = new BufferedReader(new InputStreamReader(System in));

while(true) { try { String line = reader readLine(); String words[] = line split( ); if(words[ ] equalsIgnoreCase( quit )) { System exit( ); }else if(words[ ] equalsIgnoreCase( size ) words length = ) { try { int size = Integer parseInt(words[ ]); pool setPoolSize(size); }catch(Exception e) {

}

}else if(words[ ] equalsIgnoreCase( max ) words length = ) { try { int max = Integer parseInt(words[ ]); pool setMaxPoolSize(max); }catch(Exception e) {

}

}else if(words[ ] equalsIgnoreCase( task ) words length = ) { try { int timelen = Integer parseInt(words[ ]); SimpleTask task = new SimpleTask(words[ ] timelen * ); pool processTask(task); }catch(Exception e) {

}

}

} catch (IOException e) { e printStackTrace();

}

}

}

};

cmdThread start();

/**//*

for(int i= ; i ; i++){

SimpleTask task = new SimpleTask( Task + i (i+ )* ); pool processTask(task);

}*/

}

}

class SimpleTask implements ThreadTask {

private String taskName;

private int timeLen;

public SimpleTask(String taskName int timeLen) { this taskName = taskName; this timeLen = timeLen;

}

public void run() { System out println(Thread currentThread() getId() +

: START TASK + taskName + );

try { Thread sleep(timeLen); } catch (InterruptedException e) {

}

System out println(Thread currentThread() getId() +

: END TASK + taskName + );

}

}

使用此線程池相當(dāng)簡單 下面兩行代碼初始化線程池

ThreadPool pool = new ThreadPool( ); pool init();

要處理的任務(wù)實(shí)現(xiàn)ThreadTask 接口即可(如測試代碼里的SimpleTask) 這個接口只有一個方法run()

兩行代碼即可調(diào)用

lishixinzhi/Article/program/Java/hx/201311/27203

本文標(biāo)題:java開啟線程代碼 java開啟線程的方式
分享URL:http://chinadenli.net/article2/ddegdic.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供品牌網(wǎng)站制作虛擬主機(jī)、Google手機(jī)網(wǎng)站建設(shè)、移動網(wǎng)站建設(shè)服務(wù)器托管

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

成都網(wǎng)頁設(shè)計公司