package com.woniuxy.java2;
public class MyThreadTest {
public static int ticket = 100;
public static Object lock = new Object();
public static void main(String[] args) {
SaleTicket1 s1 = new SaleTicket1();
Thread t1 = new Thread(s1,"窗口一");
Thread t2 = new Thread(s1,"窗口二");
Thread t3 = new Thread(s1,"窗口三");
t1.start();
t2.start();
t3.start();
}
}
/**
*
* @author naruto
*
*/
class SaleTicket implements Runnable{
@Override
public void run() {
String name = Thread.currentThread().getName();
while(true) {
synchronized (MyThreadTest.lock) {
if(MyThreadTest.ticket<=0) {
break;
}
MyThreadTest.ticket--;
System.out.println(name+"卖了1张票,还剩下"+MyThreadTest.ticket);
}
}
}
}
/**
* 使用同步方法
*/
class SaleTicket1 implements Runnable{
@Override
public void run() {
while(MyThreadTest.ticket>0) {
fun();
}
}
public synchronized void fun() {
String name = Thread.currentThread().getName();
if(MyThreadTest.ticket<=0) {
return;
}
MyThreadTest.ticket--;
System.out.println(name+"卖了1张票,还剩下"+MyThreadTest.ticket);
}
}