一、Thread
public class Thread implements Runnable {
}
Thread 是线程真正实现方式,所有新建线程方法最终都是通过 Thread 新建线程。
示例
class MyThread extends Thread {
private int ticket = 10;
@Override
public void run() {
while(ticket > 0){
System.out.println(this.getName() + " 卖票:" + ticket--);
}
}
}
public class ThreadTest {
public static void main(String[] args) {
// 启动3个线程t1、t2、t3,每个线程各卖10张票
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
MyThread t3 = new MyThread();
t1.start();
t2.start();
t3.start();
}
}
二、Runnable
@FunctionalInterface
public interface Runnable {
public abstract void run();
}
Runnable提供一个统一接口,规定放入线程执行的代码框架。
通过 Runnable 实现线程方式定义一个类 A 继承 Runanble,并通过 new Thread(new A()) 新建一个线程。
由于 Runable 是一个接口,并且同一个 Runnable 可以供多个线程使用,相当于资源共享,所以推荐使用 Runable。
但是有时候又会同时结合 Thread 和 Runnable 一起使用,例如线程池,一个 Thread 实例执行多个实现 Runnable 的线程。
示例
class MyRunnable implements Runnable{
private int ticket = 10;
@Override
public void run() {
while(ticket > 0){
//没有加锁,多个线程共同拥有ticket时,会有并发问题
System.out.println(Thread.currentThread().getName() + " 卖票:" + ticket--);
}
}
}
public class ThreadTest {
public static void main(String[] args) {
// 启动3个线程t1、t2、t3,每个线程各卖10张票
Thread t1 = new Thread(new MyRunnable());
Thread t2 = new Thread(new MyRunnable());
Thread t3 = new Thread(new MyRunnable());
t1.start();
t2.start();
t3.start();
// 启动3个线程t4、t5、t6,三个线程共卖10张票
MyRunnable myRunnable = new MyRunnable();
Thread t4 = new Thread(myRunnable);
Thread t5 = new Thread(myRunnable);
Thread t6 = new Thread(myRunnable);
t4.start();
t5.start();
t6.start();
}
}
三、线程池
参见【JUC线程池】篇