java 多线程Thread与runnable的区别

2025-05-29 0 42

java 多线程Thread与runnable的区别

java中实现多线程的方法有两种:继承Thread类和实现runnable接口

1,继承Thread类,重写父类run()方法

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16
public class thread1 extends Thread {

public void run() {

for (int i = 0; i < 10000; i++) {

System.out.println("我是线程"+this.getId());

}

}

public static void main(String[] args) {

thread1 th1 = new thread1();

thread1 th2 = new thread1();

th1.run();

th2.run();

}

}

run()方法只是普通的方法,是顺序执行的,即th1.run()执行完成后才执行th2.run(),这样写只用一个主线程。多线程就失去了意义,所以应该用start()方法来启动线程,start()方法会自动调用run()方法。上述代码改为:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15
public class thread1 extends Thread {

public void run() {

for (int i = 0; i < 10000; i++) {

System.out.println("我是线程"+this.getId());

}

}

public static void main(String[] args) {

thread1 th1 = new thread1();

thread1 th2 = new thread1();

th1.start();

th2.start();

}

}

通过start()方法启动一个新的线程。这样不管th1.start()调用的run()方法是否执行完,都继续执行th2.start()如果下面有别的代码也同样不需要等待th2.start()执行完成,而继续执行。(输出的线程id是无规则交替输出的)

2,实现runnable接口

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22
public class thread2 implements Runnable {

public String ThreadName;

public thread2(String tName){

ThreadName = tName;

}

public void run() {

for (int i = 0; i < 10000; i++) {

System.out.println(ThreadName);

}

}

public static void main(String[] args) {

thread2 th1 = new thread2("线程A");

thread2 th2 = new thread2("Thread-B");

th1.run();

th2.run();

}

}

和Thread的run方法一样Runnable的run只是普通方法,在main方法中th2.run()必须等待th1.run()执行完成后才能执行,程序只用一个线程。要多线程的目的,也要通过Thread的start()方法(runnable是没有start方法)。上述代码修改为:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24
public class thread2 implements Runnable {

public String ThreadName;

public thread2(String tName){

ThreadName = tName;

}

public void run() {

for (int i = 0; i < 10000; i++) {

System.out.println(ThreadName);

}

}

public static void main(String[] args) {

thread2 th1 = new thread2("线程A");

thread2 th2 = new thread2("Thread-B");

Thread myth1 = new Thread(th1);

Thread myth2 = new Thread(th2);

myth1.start();

myth2.start();

}

}

总结:实现java多线程的2种方式,runable是接口,thread是类,runnable只提供一个run方法,建议使用runable实现 java多线程,不管如何,最终都需要通过thread.start()来使线程处于可运行状态。

以上就是关于java多线程的实例详解,如有疑问请留言或者到本站社区交流讨论,本站关于线程的文章还有很多,希望大家搜索查阅,大家共同进步!

原文链接:http://szh-java.iteye.com/blog/1886650

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 java 多线程Thread与runnable的区别 https://www.kuaiidc.com/115426.html

相关文章

发表评论
暂无评论