例子,假设是个卖票系统,多个线程(例子中有2个线程)操作同一个变量ticketCount(余票的数量)。
Expected : 多个线程对同个变量会同步操作,不会造成混乱。
public class Test implements Runnable {
private String threadName;
private int ticketCount;
public Test(String threadName, int ticketCount) {
this.threadName = threadName;
this.ticketCount = ticketCount;
}
public synchronized int sellTicket() {
return ticketCount--;
}
@Override
public void run() {
// TODO Auto-generated method stub
while (ticketCount > 0) {
System.out.println(getThreadName() + " : " + sellTicket());
}
}
public String getThreadName() {
Thread a = Thread.currentThread();
return a.getName();
}
public static void main(String[] args) {
Test t1 = new Test("Ticket available ", 10);
Thread thread1 = new Thread(t1,
"1 window sell ticket ,ticket available ");
Thread thread2 = new Thread(t1,
"2 window sell ticket ,ticket available ");
thread1.start();
thread2.start();
}
}
----------------------打印结果(每次运行不一样)----------------------
2 window sell ticket ,ticket available : 9
2 window sell ticket ,ticket available : 8
2 window sell ticket ,ticket available : 7
2 window sell ticket ,ticket available : 6
2 window sell ticket ,ticket available : 5
2 window sell ticket ,ticket available : 4
1 window sell ticket ,ticket available : 10
2 window sell ticket ,ticket available : 3
1 window sell ticket ,ticket available : 2
2 window sell ticket ,ticket available : 1