Thread类和Runnable接口均能实现多线程,一般提倡用使用Runnable。原因是Java是单继承的,继承Thread就比较局限了;第二是对于资源共享时,Runnable避免了资源的重复使用。
例子:
public class App extends Thread{
private String name;
App(){}
App(String name){
this.name = name;
}
private int count =5;
public void run() {
for (int i = 0; i <= 20; i++){
while(count>0){
System.out.println(Thread.currentThread().getName() + " run " + count--);
}
}
}
public static void main(String args[]){
App a1 = new App("A");
App a2 = new App("B");
a1.start();
a2.start();
}
}
运行结果:
Thread-0 run 5
Thread-1 run 5
Thread-0 run 4
Thread-0 run 3
Thread-0 run 2
Thread-0 run 1
Thread-1 run 4
Thread-1 run 3
Thread-1 run 2
Thread-1 run 1
从结果上启动了两个线程,每个线程都运行了count一遍,重复使用。
public class App implements Runnable{
private String name;
App() {
}
private int count = 5;
public void run() {
for(int i = 0; i<10; i++) {
if(count>0) {
System.out.println(Thread.currentThread().getName() +" "+ count--);
}
}
}
public static void main(String args[]) {
App a1 = new App();
new Thread(a1).start();
new Thread(a1).start();
}
}
运行结果:
Thread-0 4
Thread-1 5
Thread-0 3
Thread-1 2
Thread-0 1
启动了两个线程,只输出5个,说明Runnable能够对资源共享。