创建线程有两种方法,一种是继承Tread类,另一种是继承Runnable接口
继承Tread类
MyThread extends Thread{
@overwrite
public void run(){
业务流程
}
}
public static void main(String[] args){
MyThread mt = new MyTread();
mt.start();
}
实现Runnable接口
MyThread implements Runnable{
@overwrite
public void run(){
业务流程
}
}
public static void main(String[] args){
MyThread mt = new MyTread();
Thread td = new Thread(mt);
td.start();
}
从代码的角度来说,实现Runnable接口比继承Thread,多了一个步骤,把要干的事塞进了一线程里(可以这么理解)
但是java是一种单继承语言,用Runnable接口就摆脱了这种缺陷,并且,对于同一个资源的消耗来说,要用Runnable接口,继承Thread类无法处理对相同资源处理的情况,即Runnable的代码,可以被多个线程(Thread实例)共享
例如多个售票窗口售票:
现有3个窗口,卖5张票
继承Thread类实现
class MyThread extends Thread{
private int ticket = 5; //总票数
private String name; //窗口号
public MyThread(String name) {
this.name=name;
}
@Override
public void run() {
while(ticket>0){
ticket--;
System.out.println(name+"买了1张票,剩余票数为:"+ticket);
}
}
}
public class TicketThread {
public static void main(String[] args) {
//创建三个线程来模拟三个售票窗口
MyThread mt1 = new MyThread("窗口1");
MyThread mt2 = new MyThread("窗口2");
MyThread mt3 = new MyThread("窗口3");
mt1.start();
mt2.start();
mt3.start();
}
}
结果为:
可以看出继承Thread类无法处理这种情况
实现Runnable接口
class MyThreadr implements Runnable{
private int ticket = 5; //总票数
@Override
public void run() {
while(ticket>0){
ticket--;
//Thread.currentThread()代表当前线程
System.out.println(Thread.currentThread().getName()+"买了1张票,剩余票数为:"+ticket);
}
}
}
public class TicketRunnableThread {
public static void main(String[] args) {
MyThreadr mt1 = new MyThreadr();
//创建三个线程来模拟三个售票窗口
//Thread有种默认的构造方法,可以这样创建线程时给线程起名
Thread td1 = new Thread(mt1,"窗口1");
Thread td2 = new Thread(mt1,"窗口2");
Thread td3 = new Thread(mt1,"窗口3");
td1.start();
td2.start();
td3.start();
}
}
结果为:
另外如果把创建线程的方式换成这样的话,那么就跟继承Thread类一样了
public static void main(String[] args) {
MyThreadr mt1 = new MyThreadr();
MyThreadr mt2 = new MyThreadr();
MyThreadr mt3 = new MyThreadr();
//创建三个线程来模拟三个售票窗口
//Thread有种默认的构造方法,可以这样创建线程时给线程起名
Thread td1 = new Thread(mt1,"窗口1");
Thread td2 = new Thread(mt2,"窗口2");
Thread td3 = new Thread(mt3,"窗口3");
td1.start();
td2.start();
td3.start();
}