售票实体类
package com.sczy.entity;
/**
* 售票类
*/
public class Safes extends Thread {
//由于卖的票是同时的,所=所以需要给售票方法加锁
private static int num = 20;
public synchronized static void sale(){
String name = Thread.currentThread().getName();
if (num>0){
//下面的线程休眠,可有可无
try {
System.out.println("当前在售票的是线程"+name+"还剩"+num--);
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
run方法所在类
package com.sczy.entity;
/**
* run方法所在的类
*/
public class Safe extends Thread {
private int num = 20;
boolean flag = true;
public void run(){
while (flag){
Safes.sale();
try {//下面的线程休眠不可以少
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
测试类
package com.sczy.test;
import com.sczy.entity.Safe;
//测试类
public class TestSafe {
public static void main(String[] args) {
//由于要实现线程联合所以,下面创建的三个线程都要同时访问sa中的资源
Safe sa = new Safe();
Thread t0 = new Thread(sa,"one");
Thread t2 = new Thread(sa,"two");
Thread t3 = new Thread(sa,"three");
t0.start();
t2.start();
t3.start();
}
}