class TicketThread extends Thread { private int ticket 10; Override public void run() { while(ticket 0) { System.out.println(getName() 卖票 ticket--); } } } public class ThreadDemo { public static void main(String[] args) { // 两个独立对象各有10张票总共卖出20张数据不共享 TicketThread t1 new TicketThread(); TicketThread t2 new TicketThread(); t1.start(); t2.start(); } }class TicketTask implements Runnable { private int ticket 10; Override public void run() { while(ticket 0) { System.out.println(Thread.currentThread().getName() 卖票 ticket--); } } } public class RunnableDemo { public static void main(String[] args) { // 同一个任务对象传入两个线程共享10张票 TicketTask task new TicketTask(); Thread t1 new Thread(task, 窗口1); Thread t2 new Thread(task, 窗口2); t1.start(); t2.start(); } }继承Thread无法共享数据Runnable可多线程共享数据。
使用Thead子类创建线程和使用Thread直接创建线程(Runnable接口)的区别?
发布时间:2026/6/25 15:59:34
class TicketThread extends Thread { private int ticket 10; Override public void run() { while(ticket 0) { System.out.println(getName() 卖票 ticket--); } } } public class ThreadDemo { public static void main(String[] args) { // 两个独立对象各有10张票总共卖出20张数据不共享 TicketThread t1 new TicketThread(); TicketThread t2 new TicketThread(); t1.start(); t2.start(); } }class TicketTask implements Runnable { private int ticket 10; Override public void run() { while(ticket 0) { System.out.println(Thread.currentThread().getName() 卖票 ticket--); } } } public class RunnableDemo { public static void main(String[] args) { // 同一个任务对象传入两个线程共享10张票 TicketTask task new TicketTask(); Thread t1 new Thread(task, 窗口1); Thread t2 new Thread(task, 窗口2); t1.start(); t2.start(); } }继承Thread无法共享数据Runnable可多线程共享数据。