1.將實(shí)現(xiàn)Runnable接口的類實(shí)例化。
2.建立一個(gè)Thread對(duì)象,并將第一步實(shí)例化后的對(duì)象作為參數(shù)傳入Thread類的構(gòu)造方法。
最后通過Thread類的start方法建立線程。
下面的代碼演示了如何使用Runnable接口來創(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();
}
}
[/code]
上面代碼的運(yùn)行結(jié)果如下:
新聞熱點(diǎn)
疑難解答
圖片精選