Java創(chuàng)建線程中的代碼詳細(xì)介紹
Java創(chuàng)建線程經(jīng)常在我們的編碼中出現(xiàn),當(dāng)我們在使用的時(shí)候會(huì)有不少的問題困擾著我們。下面我們就先來了解下有關(guān)于Java創(chuàng)建線程的相關(guān)代碼希望大家有所幫助。
- 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創(chuàng)建線程,它可安排在給定延遲后運(yùn)行命令或者定期地執(zhí)行。 ScheduledExecutorService pool = Executors.newScheduledThreadPool(2); 創(chuàng)建實(shí)現(xiàn)了Runnable接口對(duì)象,Thread對(duì)象當(dāng)然也實(shí)現(xiàn)了Runnable接口
- Thread t1 = new MyThread();
 - Thread t2 = new MyThread();
 - Thread t3 = new MyThread();
 - Thread t4 = new MyThread();
 - Thread t5 = new MyThread();
 - //將線程放入池中進(jìn)行執(zhí)行
 - pool.execute(t1);
 - pool.execute(t2);
 - pool.execute(t3);
 - //使用延遲執(zhí)行風(fēng)格的方法
 - pool.schedule(t4, 10, TimeUnit.MILLISECONDS);
 - pool.schedule(t5, 10, TimeUnit.MILLISECONDS);
 - //關(guān)閉線程池
 - pool.shutdown();
 - }
 - }
 - class MyThread extends Thread {
 - @Override
 - public void run() {
 - System.out.println(Thread.currentThread().getName() + "正在執(zhí)行。。。");
 - }
 - }
 - 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創(chuàng)建線程,它可安排在給定延遲后運(yùn)行命令或者定期地執(zhí)行。ScheduledExecutorService pool = Executors.newScheduledThreadPool(2); 創(chuàng)建實(shí)現(xiàn)了Runnable接口對(duì)象,Thread對(duì)象當(dāng)然也實(shí)現(xiàn)了Runnable接口
- Thread t1 = new MyThread();
 - Thread t2 = new MyThread();
 - Thread t3 = new MyThread();
 - Thread t4 = new MyThread();
 - Thread t5 = new MyThread();
 - //將線程放入池中進(jìn)行執(zhí)行
 - pool.execute(t1);
 - pool.execute(t2);
 - pool.execute(t3);
 - //使用延遲執(zhí)行風(fēng)格的方法
 - pool.schedule(t4, 10, TimeUnit.MILLISECONDS);
 - pool.schedule(t5, 10, TimeUnit.MILLISECONDS);
 - //關(guān)閉線程池
 - pool.shutdown();
 - }
 - }
 - class MyThread extends Thread {
 - @Override
 - public void run() {
 - System.out.println(Thread.currentThread().getName() + "正在執(zhí)行。。。");
 - }
 - } Java代碼
 - pool-1-thread-1正在執(zhí)行。。。
 - pool-1-thread-2正在執(zhí)行。。。
 - pool-1-thread-1正在執(zhí)行。。。
 - pool-1-thread-1正在執(zhí)行。。。
 - pool-1-thread-2正在執(zhí)行。。。
 - Process finished with exit code 0
 
以上就是對(duì)Java創(chuàng)建線程的詳細(xì)介紹,希望大家有所收獲。
【編輯推薦】















 
 
 
 
 
 
 