java多线程中runnable接口和thread类区别

                      java多线程中实现runnable接口和继承thread类区别

我们可以通过继承runnable接口实现多线程,也可以通过继承thread实现多线程

先来看下两种实现方式的代码。

继承thread类:

package Test;

public class testThread extends Thread{
	private int count=10;
	private String name;
    public testThread(String name) {
       this.name=name;
    }
	public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println(name + "运行  count= " + count--);
            try {
                sleep((int) Math.random() * 10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
       
	}
	public static void main(String[] args) {
			testThread mTh1=new testThread("A");
			testThread mTh2=new testThread("B");
			mTh1.start();
			mTh2.start();
	}

}

实现runnable接口:

package Test;

public class testThread implements Runnable{
	private int count=10;
    @Override
	public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println(Thread.currentThread().getName()+"运行  count= " + count--);
        }
       
	}
	public static void main(String[] args) {
			testThread mTh1=new testThread();
			new Thread(mTh1,"C").start();
			new Thread(mTh1,"D").start();
			
	}

}

运行结果:

继承thread类:

实现runnable接口:

主要区别:

1:java中不支持多继承,一旦继承了Thread类就没办法继承其他类,扩展性不好。而一个类可以实现多个接口,

这样扩展性比较好。

2:实现runnable接口是线程资源共享的,在一个线程里声明的变量,其他线程可见。对于同步操作比较容易。

而继承Thread是线程资源非共享的。每个线程都有自己的空间,声明自己的变量。如果想达到同步的目的,

就需要用到同步锁。

猜你喜欢

转载自blog.csdn.net/qq_43279637/article/details/84489134