package cn.itcast9;
/*
* 定义线程执行目标类:票
*/
public class Tickets implements Runnable {
static int number = 100;
Object lock = new Object();
int x = 0;
//重写run方法,卖票的方法
@Override
public void run() {
while(true) {
if(x%2==0) {
synchronized (Tickets.class) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(number>0) {
System.out.println(Thread.currentThread().getName()+"正在销售第"+ number +"张票");
number--;
}
}
}else {
method();
}
x++;
}
}
// //同步方法:直接在方法声明上加synchronized同步关键字修饰
// public synchronized void method() {
//// synchronized (lock) {
// try {
// Thread.sleep(10);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// if(number>0) {
// System.out.println(Thread.currentThread().getName()+"正在销售第"+ number +"张票");
// number--;
// }
//// }
// }
//静态同步方法:直接在方法声明上加synchronized同步关键字修饰
public static synchronized void method() {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(number>0) {
System.out.println(Thread.currentThread().getName()+"正在销售第"+ number +"张票");
number--;
}
}
}
|
|