Thread实现方式
- TicketThread类代码如下:
import java.util.Random; public class TicketThread extends Thread{ private static int i=1; Thread th =Thread.currentThread(); String name; public TicketThread(String name) { super(); this.name = name; } public void run() { while(i<=96) { try { th.sleep(new Random().nextInt(1000)); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } synchronized(this) { System.out.println(this.name+",出售第"+i+"张票"); i++; } } } }
- TestThread类代码如下(TicketThread)的实现类
public class TestThread { public static void main(String[] args) { TicketThread th1 = new TicketThread("窗口1"); TicketThread th2 = new TicketThread("窗口2"); TicketThread th3 = new TicketThread("窗口3"); TicketThread th4 = new TicketThread("窗口4"); TicketThread th5 = new TicketThread("窗口5"); th1.start(); th2.start(); th3.start(); th4.start(); th5.start(); } }
Runnable实现方式
- TicketRunnable类代码如下:
public class TicketRunnable implements Runnable { Thread th = Thread.currentThread(); int i = 1; public void run() { while (i <= 96) { try { th.sleep(50); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } synchronized (this) { System.out.println(Thread.currentThread().getName() + ",出售第" + i + "张票"); i++; } } } }
- TestRunnable类代码如下(TicketRunnable的实现类)
public class TestRunnable { public static void main(String[] args) { TicketRunnable tr =new TicketRunnable(); Thread th1 = new Thread(tr,"窗口1"); Thread th2 = new Thread(tr,"窗口2"); Thread th3 = new Thread(tr,"窗口3"); Thread th4 = new Thread(tr,"窗口4"); Thread th5 = new Thread(tr,"窗口5"); th1.start(); th2.start(); th3.start(); th4.start(); th5.start(); } }