实现多线程的两种方式
基本介绍
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是接口
- 一个类只能有一个父类,但是能够实现多个接口,因此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) {
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();
Thread thread1 = new Thread(runnable);
Thread thread2 = new Thread(runnable);
Thread thread3 = new Thread(runnable);
thread1.start();
thread2.start();
thread3.start();
}
}