编写一个Java 多线程程序,完成三个售票窗口同时出售20张票
程序分析:
1.票数要使用同一个静态值;
2.为保证不会出现卖出同一个票数,要java多线程同步锁。
设计思路:
创建一个站台类Station,继承Thread,重写run方法,在run方法里面执行售票操作!售票要使用同步锁:即有一个站台卖这张票时,其他站台要等这张票卖完!
2.创建主方法调用类
方法1:同步方法
public class Safe01 extends Thread{
private int num = 30;
boolean flag = true;
@Override
public void run() {
while(flag) {
sale();
try {
Thread.sleep(100);
}catch(InterruptedException e) {
e.printStackTrace();
}
}
}
//synchronized 锁的是this(也就是对象)的资源,而不是方法。
private synchronized void sale() {
if(num > 0) {
try {
Thread.sleep(100);
} catch(Exception e) {
}
System.out.println(Thread.currentThread().getName()+"卖出了第"+num--+"张票");
}else {
System.out.println("票卖完了");
flag = false;
return;
}
}
public static void main(String[] args) {
Safe01 sell = new Safe01();
Thread sell1 = new Thread(sell, "窗口1");
Thread sell2 = new Thread(sell, "窗口2");
Thread sell3 = new Thread(sell, "窗口3");
sell1.start();
sell2.start();
sell3.start();
}
}
方法2:同步块
import java.util.Date;
public class Safe03 extends Thread{
private int num = 300;
boolean flag = true;
@Override
public void run() {
while(flag) {
if(num <= 0) {
return;
}
synchronized((Integer)num) {
if(num > 0) {
System.out.println(Thread.currentThread().getName()+"卖出了第"+num--+"张票");
}else {
System.out.println("票卖完了");
flag = false;
return;
}
try {
Thread.sleep(100);
}catch(InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
Safe03 sell = new Safe03();
Thread sell1 = new Thread(sell, "窗口1");
Thread sell2 = new Thread(sell, "窗口2");
Thread sell3 = new Thread(sell, "窗口3");
sell1.start();
sell2.start();
sell3.start();
}
}
- 写的时候要注意 共享的变量尽量不要暴露在没加同步锁的地方