随笔博文

Java中 Thread 与 Runnable 的区别

2023-03-15 13:52:39 michael007js 60

多线程实现方式 定义一个线程子类,并继承Thread类。 定义一个runnable子类,实现runnable接口,并将该用runnable子类传递给一个Thread类对象。 上述使用runnable接口定义多线程的好处 在java中不允许多继承的存在,若想简介使用多继承可以利用接口来实现

若想定义一个已实现某个抽象的父类的线程时,在不使用接口时,无法继续继承Thread类,那么问题就出现了,这也就是使用runnable的好处之所在。

使用runnable接口和继承Thread类的区别 先看代码:

利用同一个runnable子类创建线程

public class Test {
 public static void main(String[] args) {
     Test test = new Test();
     MyRunnable runnable1 = test.new MyRunnable("runnable1: ");
     Thread thread1 = new Thread(runnable1);
     Thread thread2 = new Thread(runnable1);
     thread1.start();
     thread2.start();
 }

 class MyRunnable implements Runnable {
     private String name;

     public MyRunnable(String name) {
         this.name = name;
     }

     @Override
     public void run() {
         for (int i = 0; i < 6; i++) {
             System.out.println(name+" --- "+i+" ");
         }
     }

 }
}


运行结果:

这里写图片描述

定义不同runnable子类创建线程

public class Test1 {
  public static void main(String[] args) {
     Test1 test = new Test1();
     MyRunnable runnable1 = test.new MyRunnable("runnable1: ");
     MyRunnable runnable2 = test.new MyRunnable("runnable2: ");
     Thread thread1 = new Thread(runnable1);
     Thread thread2 = new Thread(runnable2);
     thread1.start();
     thread2.start();
 }

 class MyRunnable implements Runnable {
     private String name;

     public MyRunnable(String name) {
         this.name = name;
     }

     @Override
     public void run() {
         for (int i = 0; i < 6; i++) {
             System.out.println(name+" --- "+i+" ");
         }
     }

 }
}


运行结果:

这里写图片描述

通过thread子类创建线程

public class Test2 {
 public static void main(String[] args) {
     Test2 test = new Test2();
     MyThread thread1 = test.new MyThread("MyThread1");
     MyThread thread2 = test.new MyThread("MyThread2");
     thread1.start();
     thread2.start();
 }

 class MyThread extends Thread {
     private String name;

     public MyThread(String name) {
         this.name = name;
     }

     @Override
     public void run() {
         for (int i = 0; i < 6; i++) {
             System.out.println(name+" --- "+i+" ");
         }
     }

 }
}


运行结果:

这里写图片描述

通过上述代码运行结果可以看出 通过是用runnable接口创建线程时,多个线程直接会共享同一资源,如thread1和thread2都是打印i的值,但每次打印的结果一样,即重复打印。这属于并发,还未涉及到这方面知识的学习,以后研究下 当然runnable也可以实现非并发 通过thread子类处理实际上是创建两个线程去执行run方法的** 直接new一个runnable子类对象,然后调用run方法的问题: 在java中,只有Thread代表一个线程,也就是说只有new 一个Thread或其子类才能创建一个线程。 runnable在使用过程中只表示一个普通的接口而已,跟创建线程无关联 线程池的使用原理其实也就是创建一个接受runnable子类的集合,然后不断冲集合中取出runnable子类,交给线程调用其run()方法,若集合为空则线程等待。 它实际上是上一节中讲的 内部类或者说匿名内部类



首页
关于博主
我的博客
搜索