java多线程:继承Thread和实现Runable接口的区别

编程入门 行业动态 更新时间:2024-10-26 16:30:27

java<a href=https://www.elefans.com/category/jswz/34/1767532.html style=多线程:继承Thread和实现Runable接口的区别"/>

java多线程:继承Thread和实现Runable接口的区别

java中我们想要实现多线程常用的有两种方法,继承Thread 类和实现Runnable 接口,有经验的程序员都会选择实现Runnable接口 ,其主要原因有以下两点:

首先,java只能单继承,因此如果是采用继承Thread的方法,那么在以后进行代码重构的时候可能会遇到问题,因为你无法继承别的类了。

其次,如果一个类继承Thread,则不适合资源共享。但是如果实现了Runable接口的话,则很容易的实现资源共享。

1.继承Thread——多线程执行各自的资源,线程执行的资源互不干涉,各自执行各自的

public class testThread extends Thread{private int count=5;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 class main1 {public static void main(String[] args) {testThread mTh1=new testThread("A");testThread mTh2=new testThread("B");mTh1.start();mTh2.start();}
}

控制台输出(线程1和线程2之间的变量是不能共享的,每次count–都有各自的变量和结果。):

2.实现Runnable接口——多线程共享同一资源:

public class testRunnable implements Runnable{private int count=15;@Overridepublic void run() {for (int i = 0; i < 5; i++) {System.out.println(Thread.currentThread().getName() + "运行  count= " + count--);try {Thread.sleep((int) Math.random() * 10);} catch (InterruptedException e) {e.printStackTrace();}}}}public class main2 {public static void main(String[] args) {testRunnable mTh = new testRunnable();new Thread(mTh, "C").start();//同一个mTh,但是在Thread中就不可以,如果用同一个实例化对象mt,就会出现异常   new Thread(mTh, "D").start();new Thread(mTh, "E").start();}}

控制台输出(三个不同的线程之间的变量是共享的,每次count–得到的记过都是再上一个线程运行结果之上得到的。):

更多推荐

java多线程:继承Thread和实现Runable接口的区别

本文发布于:2023-07-28 22:06:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1336267.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多线程   接口   区别   java   Runable

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!