实现多线程的两种方式:
1.实现Runnable
public interface Runnable {
public abstract void run();
}
// RunnableTest.java 源码
class MyThread implements Runnable{
private int ticket=10;
public void run(){
for(int i=0;i<20;i++){
if(this.ticket>0){
System.out.println(Thread.currentThread().getName()+" 卖票:ticket"+this.ticket--);
}
}
}
};
public class RunnableTest {
public static void main(String[] args) {
MyThread mt=new MyThread();
// 启动3个线程t1,t2,t3(它们共用一个Runnable对象),这3个线程一共卖10张票!
Thread t1=new Thread(mt);
Thread t2=new Thread(mt);
Thread t3=new Thread(mt);
t1.start();
t2.start();
t3.start();
}
}
2.继承Thread
public class Thread implements Runnable {}
// ThreadTest.java 源码
class MyThread extends Thread{
private int ticket=10;
public void run(){
for(int i=0;i<20;i++){
if(this.ticket>0){
System.out.println(this.getName()+" 卖票:ticket"+this.ticket--);
}
}
}
};
public class ThreadTest {
public static void main(String[] args) {
// 启动3个线程t1,t2,t3;每个线程各卖10张票!
MyThread t1=new MyThread();
MyThread t2=new MyThread();
MyThread t3=new MyThread();
t1.start();
t2.start();
t3.start();
}
}
总结:Thread是一个类,而Runnable是一个接口,因此实现Runnable接口具有天然的扩展性优势,而且Thread有一个构造函数参数是Runnable接口的,可以共享资源。