- 實(shí)現(xiàn)Runnable接口,可以避免java單繼承機(jī)制帶來(lái)的局限;
- 實(shí)現(xiàn)Runnable接口,可以實(shí)現(xiàn)多個(gè)線程共享同一段代碼(數(shù)據(jù));
ex:
public class ThreadTest {
/**
* @param args
*/
public static void main(String[] args) {
MyThread thread1 = new MyThread();
MyThread thread2 = new MyThread();
MyThread thread3 = new MyThread();
thread1.start();
thread2.start();
thread3.start();
MyRunnable runnable1 = new MyRunnable("r1");
new Thread(runnable1).run();
new Thread(runnable1).run();
new Thread(runnable1).run();
}
}
class MyThread extends Thread
{
int things = 5;
@Override
public void run() {
while(things > 0)
{
System.out.println(currentThread().getName() + " things:" + things);
things--;
}
}
}
class MyRunnable implements Runnable
{
String name;
public MyRunnable(String name)
{
this.name = name;
}
int things = 5;
@Override
public void run() {
while(things > 0)
{
things--;
System.out.println(name + " things:" + things);
}
}
}
運(yùn)行結(jié)果:
Thread-2 things:5
r1 things:4
r1 things:3
Thread-1 things:5
Thread-1 things:4
Thread-1 things:3
r1 things:2
Thread-2 things:4
Thread-2 things:3
Thread-2 things:2
Thread-2 things:1
r1 things:1
Thread-1 things:2
r1 things:0
Thread-1 things:1
Thread-0 things:5
Thread-0 things:4
Thread-0 things:3
Thread-0 things:2
Thread-0 things:1
注解:多個(gè)Thread可以同時(shí)加載一個(gè)Runnable,當(dāng)各自Thread獲得CPU時(shí)間片的時(shí)候開始運(yùn)行runnable,runnable里面的資源是被共享的。
- 線程池只能放入實(shí)現(xiàn)Runable或Callable類線程,不能直接放入繼承Thread的類。