所谓的多线程是指一个进程在执行的过程中可以产生多个更小的程序单元,这些更小的单元称为线程,这些线程可以同时存在,同时运行。这种机制可以使程序运行的效率变得更高,也可克服传统程序语音所无法解决的问题。实现手段主要有两种:继承Thread类与实现Runnable接口。
在Thread子类中必须覆写run()方法,这是线程的主体,但是启动线程则要调用start()方法。但应该注意的是,既然是继承Thread类则一定受到了单继承的局限,但实现Runnale接口则可以实现多继承。同样实现Runnable接口也是要覆写run()方法。而启动线程则要调用public Thread(Runnable target)或public Thread (Runnable target,String name),如下:
public class TestRunnable(){
public static void main(String args[]){
MyThread mt1 = new MyThread("线程A ") ; // 实例化对象
Thread t1 = new Thread(mt1) ; // 实例化Thread类对象
t1.start() ; // 启动多线程
}
};
在使用上,Thread类与Runnable接口的最大区别为:如果一个类继承Thread类的,不适合多个线程共享资源,而如果实现了Runnable接口,则可以方便地实现资源的共享。如下:
继承Thread类:
class Thread01 extends Thread{
private int cars=3;
public void run(){
for(int i=0;i<100;i++){
if(cars>0){
System.out.println("剩下的车:cars="+--cars);
}
}
}
}
public class Example {
public static void main(String args[]){
Thread01 t1=new Thread01();
Thread01 t2=new Thread01();
t1.start();
t2.start();
}
}
剩下的车:cars=2
剩下的车:cars=2
剩下的车:cars=1
剩下的车:cars=1
剩下的车:cars=0
剩下的车:cars=0
实现Runnale接口:
class Thread02 implements Runnable{
private int cars=3;
public void run(){
for(int i=0;i<100;i++){
if(cars>0){
System.out.println("剩下的车:cars="+--cars);
}
}
}
}
public class Example02 {
public static void main(String args[]){
Thread02 t1=new Thread02();
new Thread(t1).start();
new Thread(t1).start();
}
}
剩下的车:cars=2
剩下的车:cars=1
剩下的车:cars=0
从上可见:实现Runnale 接口可以实现资源的共享,而继承Thread类不适合于多个线程共享资源。