继承 Thread 类与实现 Runnable 接口创建线程的区别及对比实验

示例 1:继承 Thread 类(资源不共享)
class TicketThread extends Thread {
private int ticket = 5; // 每个线程独立拥有5张票

@Override
public void run() {
for (int i = 0; i < 10; i++) {
if (ticket > 0) {
System.out.println(Thread.currentThread().getName()
+ " 卖票,剩余:" + --ticket);
}
}
}
}

public class ThreadTest {
public static void main(String[] args) {
// 两个线程,各自卖自己的5张票
new TicketThread().start();
new TicketThread().start();
}
}
image

示例 2:实现 Runnable 接口(资源共享)
class TicketRunnable implements Runnable {
private int ticket = 5; // 多线程共享这5张票

@Override
public void run() {
for (int i = 0; i < 10; i++) {
if (ticket > 0) {
System.out.println(Thread.currentThread().getName()
+ " 卖票,剩余:" + --ticket);
}
}
}
}

public class RunnableTest {
public static void main(String[] args) {
// 同一个任务对象,交给两个线程执行
TicketRunnable task = new TicketRunnable();
new Thread(task).start();
new Thread(task).start();
}
}
image

posted on 2026-07-05 00:28  94hc  阅读(3)  评论(0)    收藏  举报