题目
请设计一个程序模拟电影院售票,共有100张票,而它有3个售票窗口售票。
分析
3个窗口,相当于有3个线程,而3个线程右共享了100张票,所以需要使用java的内置锁,synchronized
同步代码块:锁对象可以使任意
同步方法:锁对象是 this
静态同步方法:锁对象是当前类对应的字节码文件对象
程序代码
测试类
package com.company.deno;
public class MyDemo {
public static void main(String[] args) {
SellTickets sellTickets = new SellTickets();
Thread th1 = new Thread(sellTickets);
Thread th2 = new Thread(sellTickets);
Thread th3 = new Thread(sellTickets);
th1.setName("窗口1");
th2.setName("窗口2");
th3.setName("窗口3");
th1.start();
th2.start();
th3.start();
}
}
售票
方式一:使用同步代码块
package com.company.deno;
public class SellTickets implements Runnable {
static int tickets = 100;
static Object obj = new Object();
@Override
public void run() {
while (true) {
synchronized (obj) {
if (tickets > 0) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "正在出售 " + (tickets--) + " 张票");
}else{
break;
}
}
}
}
}
方式二:使用同步方法
package com.company.deno;
public class SellTickets implements Runnable {
static int tickets = 100;
@Override
public void run() {
while (true) {
sellMethod();
}
}
private synchronized void sellMethod() { //同步方法:使用的锁对象是this
if (tickets > 0) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "正在出售 " + (tickets--) + " 张票");
}else {
System.exit(0);
}
}
}
方式三:静态同步方法
package com.company.deno;
public class SellTickets implements Runnable {
static int tickets = 100;
@Override
public void run() {
while (true) {
sellMethod();
}
}
private static synchronized void sellMethod() { //静态同步方法的锁对象:用的是当前类的字节码文件对象
if (tickets > 0) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "正在出售 " + (tickets--) + " 张票");
} else {
System.exit(0);
}
}
}