class xc implements Runnable{
public static int chePiao=100;
String a=new String("1");//字符串随意定义,定义在函数外边。
//synchronized的作用是,让它所管辖的代码部分,要么全部执行完,要么全部不执行。
public void run(){//synchronzed修饰函数不需要字符串,相当于默认是this。
while(true){
synchronized (a){//既可以修饰代码块,又可以修饰函数。
if(chePiao>0){
System.out.println("第"+Thread.currentThread().getName()+"个车站正在卖第"+(101-chePiao)+"张车票");
chePiao--;
}
else{
break;
}
}
}
}
}
public class Test{
public static void main(String[] args){
xc xc=new xc();
Thread a=new Thread(xc);
a.start();
Thread b=new Thread(xc);
b.start();
}
}<span style="white-space:pre"> </span>//用接口实现。
class xc extends Thread{
public static int chePiao=100;
public static String a=new String("1");//变成公共静态的。
//synchronized的作用是,让它所管辖的代码部分,要么全部执行完,要么全部不执行。
public void run(){//synchronzed修饰函数不需要字符串,相当于默认是this。
while(true){
synchronized (a){//两个线程的a是线程自己的,并不是公共的,所以我们要把a变成公共的。
if(chePiao>0){
System.out.println("第"+Thread.currentThread().getName()+"个车站正在卖第"+(101-chePiao)+"张车票");
chePiao--;
}
else{
break;
}
}
}
}
}
public class Test{
public static void main(String[] args){
xc xc=new xc();
xc.start();
xc xc2=new xc();
xc2.start();
}
}<span style="white-space:pre"> </span>//用继承实现。