上锁前
package gcallable;
public class UnsafeBuyTicket {
public static void main(String[] args) {
BuyTickets buyTickets = new BuyTickets();
new Thread(buyTickets,"luck").start();
new Thread(buyTickets,"jack").start();
new Thread(buyTickets,"monkey").start();
new Thread(buyTickets,"tony").start();
}
}
class BuyTickets implements Runnable{
private int tickets=10;
private boolean flag=true;
@Override
public void run() {
while (flag) {
buy();
}
}
private void buy() {
if (tickets<0) {
flag=false;
return;
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"拿到了"+tickets--);
}
}
monkey拿到了10
luck拿到了9
jack拿到了9
tony拿到了8
luck拿到了7
jack拿到了6
monkey拿到了4
tony拿到了5
luck拿到了2
monkey拿到了3
jack拿到了3
tony拿到了1
tony拿到了0
luck拿到了0
monkey拿到了-1
jack拿到了0
上锁后
package gcallable;
public class UnsafeBuyTicket {
public static void main(String[] args) {
BuyTickets buyTickets = new BuyTickets();
new Thread(buyTickets,"luck").start();
new Thread(buyTickets,"jack").start();
new Thread(buyTickets,"monkey").start();
new Thread(buyTickets,"tony").start();
}
}
class BuyTickets implements Runnable{
private int tickets=10;
private boolean flag=true;
@Override
public void run() {
while (flag) {
buy();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private synchronized void buy() {
if (tickets<=0) {
flag=false;
return;
}
System.out.println(Thread.currentThread().getName()+"拿到了"+tickets--);
}
}
luck拿到了10
monkey拿到了9
tony拿到了8
jack拿到了7
monkey拿到了6
luck拿到了5
tony拿到了4
jack拿到了3
luck拿到了2
monkey拿到了1