Java創建線程中的代碼詳細介紹
Java創建線程經常在我們的編碼中出現,當我們在使用的時候會有不少的問題困擾著我們。下面我們就先來了解下有關于Java創建線程的相關代碼希望大家有所幫助。
- import java.util.concurrent.Executors;
- import java.util.concurrent.ScheduledExecutorService;
- import java.util.concurrent.TimeUnit;
- /**
- * Java線程:線程池-
- *
- * @author Administrator 2009-11-4 23:30:44
- */
- public class Test {
- public static void main(String[] args) {
Java創建線程,它可安排在給定延遲后運行命令或者定期地執行。 ScheduledExecutorService pool = Executors.newScheduledThreadPool(2); 創建實現了Runnable接口對象,Thread對象當然也實現了Runnable接口
- Thread t1 = new MyThread();
- Thread t2 = new MyThread();
- Thread t3 = new MyThread();
- Thread t4 = new MyThread();
- Thread t5 = new MyThread();
- //將線程放入池中進行執行
- pool.execute(t1);
- pool.execute(t2);
- pool.execute(t3);
- //使用延遲執行風格的方法
- pool.schedule(t4, 10, TimeUnit.MILLISECONDS);
- pool.schedule(t5, 10, TimeUnit.MILLISECONDS);
- //關閉線程池
- pool.shutdown();
- }
- }
- class MyThread extends Thread {
- @Override
- public void run() {
- System.out.println(Thread.currentThread().getName() + "正在執行。。。");
- }
- }
- import java.util.concurrent.Executors;
- import java.util.concurrent.ScheduledExecutorService;
- import java.util.concurrent.TimeUnit;
- /**
- * Java線程:線程池-
- *
- * @author Administrator 2009-11-4 23:30:44
- */
- public class Test {
- public static void main(String[] args) {
Java創建線程,它可安排在給定延遲后運行命令或者定期地執行。ScheduledExecutorService pool = Executors.newScheduledThreadPool(2); 創建實現了Runnable接口對象,Thread對象當然也實現了Runnable接口
- Thread t1 = new MyThread();
- Thread t2 = new MyThread();
- Thread t3 = new MyThread();
- Thread t4 = new MyThread();
- Thread t5 = new MyThread();
- //將線程放入池中進行執行
- pool.execute(t1);
- pool.execute(t2);
- pool.execute(t3);
- //使用延遲執行風格的方法
- pool.schedule(t4, 10, TimeUnit.MILLISECONDS);
- pool.schedule(t5, 10, TimeUnit.MILLISECONDS);
- //關閉線程池
- pool.shutdown();
- }
- }
- class MyThread extends Thread {
- @Override
- public void run() {
- System.out.println(Thread.currentThread().getName() + "正在執行。。。");
- }
- } Java代碼
- pool-1-thread-1正在執行。。。
- pool-1-thread-2正在執行。。。
- pool-1-thread-1正在執行。。。
- pool-1-thread-1正在執行。。。
- pool-1-thread-2正在執行。。。
- Process finished with exit code 0
以上就是對Java創建線程的詳細介紹,希望大家有所收獲。
【編輯推薦】