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

实现多线程的两种方式

  • 常用的实现多线程的两种方式:
    • 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();
	}
}
  • 不会出现处理同一个资源的情况

猜你喜欢

转载自blog.csdn.net/JewaveOxford/article/details/108097242