Use synchronized (object) to achieve thread safety
package com.dwz.concurrency.chapter7; public class TicketWindowRunnable implements Runnable { private int index = 1; private final static int MAX = 500; private final Object MONITOR = new Object(); @Override public void run() { while(true) { synchronized (MONITOR) { if(index > MAX) { break; } try { Thread.sleep(5); } catch (InterruptedException e) { e.printStackTrace (); } System.out.println (Thread.currentThread () + "number is:" + (index ++ )); } } } }
Test code
package com.dwz.concurrency.chapter7; 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(); } }