使用多线程模拟一个银行叫号窗口
使用继承Thread类的方式创建线程
银行叫号部分的代码
package com.dwz.concurrency.chapter2; /** * 使用static保证号码数据共享 * 线程的创建方式:继承Thread类 */ public class TicketWindow extends Thread{ private static final int MAX = 100; //号码 private static int index = 1; private final String name; public TicketWindow(String name) { this.name = name; } @Override public void run() { while(index <= MAX) { System.out.println(name + "当前的号码是:" + (index++)); } } }
测试代码:
package com.dwz.concurrency.chapter2; public class Bank { public static void main(String[] args) { TicketWindow tw = new TicketWindow("一号柜台"); tw.start(); TicketWindow tw2 = new TicketWindow("二号柜台"); tw2.start(); TicketWindow tw3 = new TicketWindow("三号柜台"); tw3.start(); } }
使用实现Runnable接口的方式创建线程
银行叫号部分的代码
package com.dwz.concurrency.chapter2; /** * 实现业务逻辑和线程的分离 */ public class TicketWindowRunnable implements Runnable { private static final int MAX = 100000; private int index = 1; public void run() { while(index <= MAX) { System.out.println(Thread.currentThread().getName() + " 的号码是:" + (index++)); } } }
测试代码:
package com.dwz.concurrency.chapter2; /** * 此方式可以保证TicketWindowRunnable类被实例化一次 * 三个线程共用一个TicketWindowRunnable对象,达到共享号码的目的 */ public class BankVersion2 { public static void main(String[] args) { TicketWindowRunnable wr = new TicketWindowRunnable(); Thread thread1 = new Thread(wr, "柜台一"); Thread thread2 = new Thread(wr, "柜台二"); Thread thread3 = new Thread(wr, "柜台三"); thread1.start(); thread2.start(); thread3.start(); } }