thread == 售票

import org.apache.xerces.util.SymbolTable;

public class ThreadDemo1 {
public static void main(String[] args){
Saler s1 = new Saler("wang");
Saler s2 = new Saler("zhang");
s1.start();
s2.start(); }
} //class Saler extends Thread{
//// static Object lock = new Object();
// static int tickets = 100;
// private String name;
// public Saler(String name){
// this.name = name;
// }
// public void run() {
// while (tickets>0) {
// int currstk = tickets;
// tickets -= 1;
// System.out.println(this.name+"====》》》》》"+currstk);
//
// }
// };
//} //class Saler extends Thread{
// static Object lock = new Object(); //java 中一切皆对象,因此,锁只是一个相对元素,是多个线程的共有的一个参照物而已。
// static int tickets = 100;//所有线程共同访问的一个元素
// private String name;
// public Saler(String name){
// this.name = name;
// }
// public void run() {
// while (tickets>0) {
// synchronized(lock) { // 同步代码块 会查看锁的状态,抢占锁,获取锁的,才能执行下面的代码,执行完毕之后,释放锁
// int currstk = tickets;
// tickets -= 1;
// System.out.println(this.name + "====》》》》》" + currstk);
// }
// }
// };
//} class Saler extends Thread{
static int tickets = 100;//所有线程共同访问的一个元素
private String name;
public Saler(String name){
this.name = name;
}
public void run() {
while (tickets>0) {
int currTicks = getTickets();
System.out.println(this.name+">>>>>>>>>>> "+currTicks);
}
}
//同步方法
//非静态 以当前对象作为锁旗标
//静态:以类作为锁旗标。
public static synchronized int getTickets(){ // 以类作为共同的参照物,如果不加static就是以各自作为参照物。那么就是各自参考自己,
//没有统一的标准了,也就没有所谓的同步了。
int curr = tickets;
tickets -=1;
return curr;
}
};
上一篇:一段C程序分析


下一篇:C语言共用体(Union)