【代码说明】
两个线程“Window1”和“Window2”操作同一变量ticketCount(卖票)。
【代码示例】
1、MyThread.java
package com.wcs.java.thread;
public class MyThread implements Runnable{
private int ticketCount;
public MyThread(int ticketCount) {
this.ticketCount = ticketCount;
}
public synchronized int sellTicket() {
return --ticketCount;
}
@Override
public void run() {
while(ticketCount > 0) {
System.out.println(Thread.currentThread().getName() + " sell one ticket,remainder ticket count is : " + sellTicket());
}
}
}
2、TestMyThread.java
package com.wcs.java.thread;
public class TestMyThread {
public static void main(String[] args) {
MyThread myThread = new MyThread(10);
Thread t1 = new Thread(myThread, "Window 1");
Thread t2 = new Thread(myThread, "Window 2");
t1.start();
t2.start();
}
}
【运行结果】
Window 1 sell one ticket,remainder ticket count is : 9
Window 1 sell one ticket,remainder ticket count is : 7
Window 1 sell one ticket,remainder ticket count is : 6
Window 2 sell one ticket,remainder ticket count is : 8
Window 2 sell one ticket,remainder ticket count is : 4
Window 2 sell one ticket,remainder ticket count is : 3
Window 2 sell one ticket,remainder ticket count is : 2
Window 2 sell one ticket,remainder ticket count is : 1
Window 2 sell one ticket,remainder ticket count is : 0
Window 1 sell one ticket,remainder ticket count is : 5