Java多線程初學者指南(3):使用Runnable接口創建線程
本文為原創,如需轉載,請注明作者和出處,謝謝!
上一篇:Java多線程初學者指南(2):用Thread類創建線程
實現Runnable接口的類必須使用Thread類的實例才能創建線程。通過Runnable接口創建線程分為兩步:
1. 將實現Runnable接口的類實例化。
2. 建立一個Thread對象,并將第一步實例化后的對象作為參數傳入Thread類的構造方法。
最后通過Thread類的start方法建立線程。
下面的代碼演示了如何使用Runnable接口來創建線程:
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();
}
}
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();
}
}
上面代碼的運行結果如下:
MyThread1
MyThread2
MyThread2
下一篇:Java多線程初學者指南(4):線程的生命周期
《Android高薪之路:Android程序員面試寶典 》http://book.360buy.com/10970314.html
新浪微博:http://t.sina.com.cn/androidguy 昵稱:李寧_Lining
posted on 2009-03-10 11:56 銀河使者 閱讀(5875) 評論(0) 編輯 收藏 所屬分類: java 、 原創 、多線程