Java單任務延遲連接池在四代碼基礎上做改動這個就需要我們不選的學習下面我們就看看如何才能更好的使用希望我們在下面的使用中大家更了解相關的代碼
Java <>單任務延遲代碼
創建一個單線程執行程序它可安排在給定延遲後運行命令或者定期地執行
ScheduledExecutorService pool = ExecutorsnewSingleThread
ScheduledExecutor();
創建一個單線程執行程序它可安排在給定延遲後運行命令或者定期地執行
ScheduledExecutorService pool = ExecutorsnewSingle
ThreadScheduledExecutor();
Java代碼
poolthread正在執行
poolthread正在執行
poolthread正在執行
poolthread正在執行
poolthread正在執行
Process finished with exit code
poolthread正在執行
poolthread正在執行
poolthread正在執行
poolthread正在執行
poolthread正在執行
Process finished with exit code
自定義線程池
Java代碼
import ncurrentArrayBlockingQueue;
import ncurrentBlockingQueue;
import ncurrentThreadPoolExecutor;
import ncurrentTimeUnit;
/**
* Java線程線程池自定義線程池
*
* @author Administrator ::
*/
public class Test {
public static void main(String[] args) {
//創建等待隊列
BlockingQueue<Runnable> bqueue = new ArrayBlockingQueue
<Runnable>();
//創建一個單線程執行程序它可安排在給定延遲後運行命令或者定期地執行
ThreadPoolExecutor pool = new ThreadPoolExecutor
(TimeUnitMILLISECONDSbqueue);
//創建實現了Runnable接口對象Thread對象當然也實現了Runnable接口
Thread t = new MyThread();
Thread t = new MyThread();
Thread t = new MyThread();
Thread t = new MyThread();
Thread t = new MyThread();
Thread t = new MyThread();
Thread t = new MyThread();
//將線程放入池中進行執行
poolexecute(t);
poolexecute(t);
poolexecute(t);
poolexecute(t);
poolexecute(t);
poolexecute(t);
poolexecute(t);
//關閉線程池
poolshutdown();
}
}
class MyThread extends Thread {
@Override
public void run() {
Systemoutprintln(ThreadcurrentThread()getName() +
正在執行);
try {
Threadsleep(L);
} catch (InterruptedException e) {
eprintStackTrace();
}
}
}
import ncurrentArrayBlockingQueue;
import ncurrentBlockingQueue;
import ncurrentThreadPoolExecutor;
import ncurrentTimeUnit;
/**
* Java線程線程池自定義線程池
*
* @author Administrator ::
*/
public class Test {
public static void main(String[] args) {
//創建等待隊列
BlockingQueue<Runnable> bqueue = new ArrayBlockingQueue
<Runnable>();
//創建一個單線程執行程序它可安排在給定延遲後運行命令或者定期地執行
ThreadPoolExecutor pool = new ThreadPoolExecutor
(TimeUnitMILLISECONDSbqueue);
//創建實現了Runnable接口對象Thread對象當然也實現了Runnable接口
Thread t = new MyThread();
Thread t = new MyThread();
Thread t = new MyThread();
Thread t = new MyThread();
Thread t = new MyThread();
Thread t = new MyThread();
Thread t = new MyThread();
//將線程放入池中進行執行
poolexecute(t);
poolexecute(t);
poolexecute(t);
poolexecute(t);
poolexecute(t);
poolexecute(t);
poolexecute(t);
//關閉線程池
poolshutdown();
}
}
class MyThread extends Thread {
@Override
public void run() {
Systemoutprintln(ThreadcurrentThread()getName() +
正在執行);
try {
Threadsleep(L);
} catch (InterruptedException e) {
eprintStackTrace();
}
}
}
Java代碼
poolthread正在執行
poolthread正在執行
poolthread正在執行
poolthread正在執行
poolthread正在執行
poolthread正在執行
poolthread正在執行
Process finished with exit code
poolthread正在執行
poolthread正在執行
poolthread正在執行
poolthread正在執行
poolthread正在執行
poolthread正在執行
poolthread正在執行
以上就是對Java單任務延遲的相關代碼介紹
From:http://tw.wingwit.com/Article/program/Java/hx/201311/25732.html