概要
常用的实现多线程有两种方法,1:继承Thread类,2:实现Runnable接口。
之所以说是常用,是因为还可以使用JUC(java.util.concurrent)包中的线程池来实现多线程。首先我们对常用的Thread类和Runnable接口进行了解说明。
Thread类和Tunnable接口简介
Runnable是一个接口,该接口中只包含了run方法,定义如下
public interface Runnable {
public abstract void run();
}
Runnable接口的作用就是用来实现多线程,我们可以定一个类A实现Runnable接口,然后通过new Thread(new A())等方式创建
Thread类本身就实现了Runnable接口,声明如下
public class Thread implements Runnable {}
Thread类的作用,实现多线程。
两者异同点
相同点:都是多线程的实现方式
不同点:Thread是类,Runnable是接口,Thread类还实现了Runnable接口,我们知道一个类只可以有一个父类,但是可以有实现多个接口,所以接口的拓展性更好。此外,Runnable接口可以用于资源共享,即多个线程都基于一个Runnable对象简历的,他们会共享Runnable对象上的资源。因此一般推荐使用Runnable接口实现多线程。
1,Thread的多线程示例
// 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-0 卖票:ticket10
Thread-1 卖票:ticket10
Thread-2 卖票:ticket10
Thread-1 卖票:ticket9
Thread-0 卖票:ticket9
Thread-1 卖票:ticket8
Thread-2 卖票:ticket9
Thread-1 卖票:ticket7
Thread-0 卖票:ticket8
Thread-1 卖票:ticket6
Thread-2 卖票:ticket8
Thread-1 卖票:ticket5
Thread-0 卖票:ticket7
Thread-1 卖票:ticket4
Thread-2 卖票:ticket7
Thread-1 卖票:ticket3
Thread-0 卖票:ticket6
Thread-1 卖票:ticket2
Thread-2 卖票:ticket6
Thread-2 卖票:ticket5
Thread-2 卖票:ticket4
Thread-1 卖票:ticket1
Thread-0 卖票:ticket5
Thread-2 卖票:ticket3
Thread-0 卖票:ticket4
Thread-2 卖票:ticket2
Thread-0 卖票:ticket3
Thread-2 卖票:ticket1
Thread-0 卖票:ticket2
Thread-0 卖票:ticket1
结果说明:
(01) MyThread继承于Thread,它是自定义个线程。每个MyThread都会卖出10张票。
(02) 主线程main创建并启动3个MyThread子线程。每个子线程都各自卖出了10张票。
2,Runnable的多线程示例
// 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();
}
}
运行结果:
Thread-0 卖票:ticket10
Thread-2 卖票:ticket8
Thread-1 卖票:ticket9
Thread-2 卖票:ticket6
Thread-0 卖票:ticket7
Thread-2 卖票:ticket4
Thread-1 卖票:ticket5
Thread-2 卖票:ticket2
Thread-0 卖票:ticket3
Thread-1 卖票:ticket1
结果说明:
(01) 和上面“MyThread继承于Thread”不同;这里的MyThread实现了Thread接口。
(02) 主线程main创建并启动3个子线程,而且这3个子线程都是基于“mt这个Runnable对象”而创建的。运行结果是这3个子线程一共卖出了10张票。这说明它们是共享了MyThread接口的。