class Xc implements Runnable{
public static int chepiao=20;//static 所有对象共享100张票
public static String a=new String("1");//字符串随意定义,定义在函数上边
//synchronized(修饰函数,,不需要字符串,相当于默认是this让它所管辖的代码部分,要么全部执行完,要么全部不执行
public void run(){
while(true){
synchronized(a){//既可以修饰代码块,又可以修饰函数
if(chepiao>0){
System.out.println("第"+Thread.currentThread().getName()+"个车站正在卖第"+(21-chepiao)+"张车票");
--chepiao;
}
else{
break;
}
}
}
}
}
public class Test{
public static void main(String[] args){
Xc xc1=new Xc();
Thread ee=new Thread(xc1);
ee.start();
Xc xc2=new Xc();
Thread ff=new Thread(xc2);
ff.start();
}
}
class Xc extends Thread{
public static int chepiao=20;
public static String a=new String("1");
public void run(){
while(true){
synchronized(a){
if(chepiao>0){
System.out.println("第"+Thread.currentThread().getName()+"个车站正在卖第"+(21-chepiao)+"张车票");
--chepiao;
}
else{
break;
}
}
}
}
}
public class Test{
public static void main(String[] args){
Xc xc1=new Xc();
xc1.start();
Xc xc2=new Xc();
xc2.start();
}
}