多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
# Runnable接口改进排队叫号 接下来通过Runnable实现一下我们之前的排队叫号感受一下 ```java /** * @program: ThreadDemo * @description: 银行大厅 * @author: hs96.cn@Gmail.com * @create: 2020-08-28 */ public class BankRunnable { public static void main(String[] args) { //一个runnable实例被多个线程共享 TicketWindowRunnable ticketWindow = new TicketWindowRunnable(); Thread windowThread1 = new Thread(ticketWindow, "一号窗口"); Thread windowThread2 = new Thread(ticketWindow, "二号窗口"); Thread windowThread3 = new Thread(ticketWindow, "三号窗口"); windowThread1.start(); windowThread2.start(); windowThread3.start(); } } ``` ```java /** * @program: ThreadDemo * @description: 柜台,业务处理窗口。继承Runnable接口 * @author: hs96.cn@Gmail.com * @create: 2020-08-28 */ public class TicketWindowRunnable implements Runnable { private int index = 1; private static final int MAX = 50; @Override public void run() { while (index <= MAX) { System.out.println(Thread.currentThread().getName() + " 的号码是:" + (index++)); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } } ``` 可以看到 index没有被static修饰,一个runnable实例被多个线程共享了,运行效果如下: ![](https://img.kancloud.cn/9c/97/9c97241894065b1056dec284b53322e4_1153x382.gif) 能达到我们的目的,但是这种写法更加好,线程的逻辑全封装到一个实例中,所以这也是Runnable存在的必要性。