新聞中心
這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷(xiāo)解決方案
初學(xué)Java多線程:使用Runnable接口創(chuàng)建線程
實(shí)現(xiàn)Runnable接口的類(lèi)必須使用Thread類(lèi)的實(shí)例才能創(chuàng)建線程。通過(guò)Runnable接口創(chuàng)建線程分為兩步:

1. 將實(shí)現(xiàn)Runnable接口的類(lèi)實(shí)例化。
2. 建立一個(gè)Thread對(duì)象,并將第一步實(shí)例化后的對(duì)象作為參數(shù)傳入Thread類(lèi)的構(gòu)造方法。
最后通過(guò)Thread類(lèi)的start方法建立線程。
下面的代碼演示了如何使用Runnable接口來(lái)創(chuàng)建線程:
- package mythread;
- public class MyRunnable implements Runnable
- {
- public void run()
- {
- System.out.println(Thread.currentThread().getName());
- }
- public static void main(String[] args)
- {
- MyRunnable t1 = new MyRunnable();
- MyRunnable t2 = new MyRunnable();
- Thread thread1 = new Thread(t1, "MyThread1");
- Thread thread2 = new Thread(t2);
- thread2.setName("MyThread2");
- thread1.start();
- thread2.start();
- }
- }
上面代碼的運(yùn)行結(jié)果如下:
MyThread1
MyThread2
舉例Java多線程的學(xué)習(xí)又更近一步了。
【編輯推薦】
- 初學(xué)Java多線程:用Thread類(lèi)創(chuàng)建線程
- 初學(xué)Java多線程:線程簡(jiǎn)介
- Java多線程編程的常見(jiàn)陷阱
- Java多線程的相關(guān)機(jī)制
- Java多線程學(xué)習(xí)總結(jié)(二)
本文名稱:初學(xué)Java多線程:使用Runnable接口創(chuàng)建線程
瀏覽路徑:http://m.fisionsoft.com.cn/article/coeddch.html


咨詢
建站咨詢
