Java多线程实现——Runnable和Thread的区别

快来打我* 2022-05-13 05:14 347阅读 0赞

synchronized ThreadLocal

转载:https://blog.csdn.net/shakespeare001/article/details/51321498

1.实现Runnable:

  1. package com;
  2. public class HelloWorld implements Runnable{
  3. private int num=0;
  4. public static void main(String[] args){
  5. HelloWorld hw=new HelloWorld();
  6. new Thread(hw).start();
  7. new Thread(hw).run();
  8. }
  9. public void run() {
  10. System.out.println("开始运行");
  11. for(int i=0;i<5;i++) {
  12. System.out.println(num++);
  13. }
  14. }
  15. }

运行结果:我尝试运行了多次,大概有一下这两种结果:

70

70 1

  1. package com;
  2. public class HelloWorld implements Runnable{
  3. private int num=0;
  4. public static void main(String[] args){
  5. HelloWorld hw=new HelloWorld();
  6. new Thread(hw).start();
  7. new Thread(hw).start();
  8. }
  9. public void run() {
  10. System.out.println("开始运行");
  11. for(int i=0;i<5;i++) {
  12. System.out.println(num++);
  13. }
  14. }
  15. }

运行结果:

有以下几种:

70 2

70 3

70 4

70 5

70 6

2.继承 Thread

  1. package com;
  2. public class HelloWorld extends Thread{
  3. private int num=0;
  4. public static void main(String[] args){
  5. new HelloWorld().start();
  6. new HelloWorld().start();
  7. }
  8. public void run() {
  9. System.out.println("开始运行");
  10. for(int i=0;i<5;i++) {
  11. System.out.println(num++);
  12. }
  13. }
  14. }

运行结果:

70 7

70 8

70 9

分析 :继承(extends)自Thread来实现多线程时,每个线程都独立拥有一份自己的变量,各个线程之间不能实现资源的共享;而实现(implements)Runnable来实现多线程时,可以实现各个线程之间资源的共享。

发表评论

表情:
评论列表 (有 0 条评论,347人围观)

还没有评论,来说两句吧...

相关阅读