继承Thread和实现Runnable接口的区别
1.从java设计来看:通过继承Thread或者实现Runnable接口来穿件线程本质上是没有区别的,从jdk帮助文档我们可以看到Thread类本身就实现了Runnable接口。
2.实现Runnable接口方式更加适合多个线程共享一个资源的情况,并且避免了单继承的限制!
多线程实现方式
请编写一个程序,创建两个线程,一个线程输出"执行听歌",输出一百次。退出,另一个线程输出一次输出"执行游戏"一百次,退出。
继承thread
public class Mythread1 extends Thread{
@Override
public void run(){
for (int i=0;i<100;i++){
System.out.println("执行听歌"+i);
}
}
}
public class Mythread2 extends Thread{
@Override
public void start(){
for (int j=0;j<100;j++){
System.out.println("执行游戏"+j);
}
}
}
public class Threadtext1 {
public static void main(String[] args) {
Mythread1 t1=new Mythread1();
Mythread2 t2=new Mythread2();
t1.start();
t2.start();
}
}
实现Runnable
public class MyRunnable1 implements Runnable{
@Override
public void run() {
for (int i=0;i<100;i++){
System.out.println("执行听歌"+i);
}
}
}
public class MyRunnable2 implements Runnable {
@Override
public void run() {
for (int j=0;j<100;j++){
System.out.println("执行游戏"+j);
}
}
}
public class Threadtext2 {
/**
* Runnable接口实现类实现多线程的步骤:
* 1.定义类实现Rdhnable接口:
* 2.重写run方法;
* 3.在main方法中实例化Runnable接口的实现类对象;
* 4.定义两个线程Thread类的对象,把Runnable接口的实现对象传入构造方法中;
* 10 5.线程类对象调用start方法,启动线程,自动执行Runnable接口的实现类中的run方法;
*/
public static void main(String[] args) {
MyRunnable1 r1=new MyRunnable1();
MyRunnable2 r2=new MyRunnable2();
//Runnable接口的实现实现多线程,必须借助Thread类才能实现
Thread t1=new Thread(r1);
Thread t2=new Thread(r2);
1402

被折叠的 条评论
为什么被折叠?



