//代碼
class ThreadSelllandRefund implements Runnable{
private int tickets=0;
@Override
public void run() {
// TODO Auto-generated method stub
String name=Thread.currentThread().getName();
if(name.equals("退票視窗")) {
for(int i=0;i<3;i++) {
try {
Thread.sleep(10);
}
catch(InterruptedException e) {
e.printStackTrace();
}
refund();
}
}
if(name.contains("售票視窗")) {
for(int i=0;i<1;i++) {
sell();
}
}
}
private synchronized void sell() {
if(tickets>0) {
System.out.println(Thread.currentThread().getName()+"售出一張車票,車票余量為"+(--tickets)+"張");
}else {
System.out.println(Thread.currentThread().getName()+"說:車票已經售完,請等待退票!");
try {
wait();
}
catch(InterruptedException e) {
e.printStackTrace();
}
}
}
private synchronized void refund() {
tickets++;
System.out.println(Thread.currentThread().getName()+"退回一張車票,車票余量為"+(tickets)+"張");
notify();
}
}
public class ticketsnotify_demo extends Thread{
public static void main(String[] args) {
ThreadSelllandRefund t=new ThreadSelllandRefund();
Thread thread3=new Thread(t,"退票視窗");
Thread thread1=new Thread(t,"售票視窗A");
Thread thread2=new Thread(t,"售票視窗B");
thread1.setPriority(Thread.MIN_PRIORITY);
thread2.setPriority(Thread.MIN_PRIORITY);
thread3.setPriority(Thread.MAX_PRIORITY);
thread3.start();
thread1.start();
thread2.start();
}
}
//問題:為什么我設定退票的優先級最高,可以程式都是先執行售票呢?如下圖

按理說,先退票的話,就只剩一張票了吧,可是結果卻有3張票,代碼附上
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/228159.html
標籤:Java相關
上一篇:各位大佬,我用的自定義函式總是有問題,又找不出錯在哪兒了,求幫忙
下一篇:怎么弄
