0
点赞
收藏
分享

微信扫一扫

Java多线程Day02-多线程之实现多线程的两种方式



实现多线程的两种方式


  • ​​实现多线程的两种方式​​

  • ​​基本介绍​​

  • ​​Thread​​
  • ​​Runnable​​

  • ​​Thread和Runnable比较​​

  • ​​相同点​​
  • ​​不同点​​


  • ​​Thread实现多线程​​
  • ​​Runnable实现多线程​​


实现多线程的两种方式

  • 常用的实现多线程的两种方式:

  • Thread
  • Runnable

基本介绍

Thread

  • 作用:​ 实现多线程
  • Thread​是一个类,本身实现了​Runnable​接口:

public class Thread implements Runnable {}
Runnable

  • 作用:​ 实现多线程

  • 可以定义一个类​A​实现​Runnable​接口
  • 然后通过​new Thread(new A())​ 方式新建线程

  • Runnable是一个接口,该接口中只包含了一个​run​方法:

public interface Runnable {
public abstract void run();
}

Thread和Runnable比较

相同点
  • 都是用于实现多线程
不同点

  • Thread​是类 ​,Runnable​是接口
  • Thread​本身是实现了​Runnable​接口的类
  • 一个类只能有一个父类,但是能够实现多个接口,因此​Runnable​具有更好的扩展性
  • Runnable​可以用于资源的共享:
  • 多个线程都是基于某一个​Runnable​对象建立的,会共享​Runnable​对象上的资源
  • 通常建议使用Runnable实现多线程

Thread实现多线程

class Threads extends Thread {
private int tickets = 20;
public void run() {
for (int i = 0; i < 20; i++) {
if (ticket > 0) {
System.out.println(this.getName(), this.ticket--);
}
}
}
};

public class ThreadTest {
public void main(String[] args) {
// 启动3个线程,各自线程的资源都为 tickets=20
Threads thread1 = new Threads();
Threads thread2 = new Threads();
Threads thread3 = new Threads();

thread1.start();
thread2.start();
thread3.start();
}
}
  • 可能会出现争抢,同时处理同一个资源

Runnable实现多线程

class Threads implements Runnable {
private int tickets = 20;
for (int i = 0; i < 20; i++) {
if (ticket > 0) {
System.out.println(this.getName(), this.ticket--);
}
}
};

public class RunnableTest {
public static void main(String[] args) {
Threads runnable = new Threads();

// 启动3个共用一个Runnable对象的线程,共享资源.这3个线程总体资源为ticket=20
Thread thread1 = new Thread(runnable);
Thread thread2 = new Thread(runnable);
Thread thread3 = new Thread(runnable);

thread1.start();
thread2.start();
thread3.start();
}
}
  • 不会出现处理同一个资源的情况


举报

相关推荐

0 条评论