银行窗口取号系统,共享数据的线程安全性
对共享数据的访问和修改要在同步代码块里
同步代码块的代码是顺序执行的,所以能够保证共享数据的安全性
public class Demo { public static void main(String[] args) { Runnable runnable = new WindowRunnable(); new Thread(runnable, "窗口1").start(); new Thread(runnable, "窗口2").start(); new Thread(runnable, "窗口3").start(); } static class WindowRunnable implements Runnable { final Object monitor = new Object(); int index = 0; // index是共享数据,对共享数据的访问和修改要在同步代码块里 static final int MAX = 50; @Override public void run() { while (true) { synchronized (monitor) { if (index < MAX) { printMsg(); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } } } public void printMsg() { System.out.println(Thread.currentThread().getName() + ": " + (++index)); } } }