add package ticket

This commit is contained in:
xixu-me committed 2024-04-22 23:27:46 +08:00
1 parent 45da627b83
commit 67e31dba87
2 files changed
+103

No files matched your search

+29
View File
@@ -0,0 +1,29 @@
package ticket;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
TicketSeller ts = new TicketSeller(1, 1, 1, 1, 1);
String name;
int payment;
boolean continueBuy = true;
Scanner sc = new Scanner(System.in);
while (continueBuy) {
System.out.print("Please enter your name: ");
name = sc.next();
System.out.print("Please enter your payment: ");
payment = sc.nextInt();
Thread consumer = new Thread(ts, name + "-" + payment);
consumer.start();
try {
consumer.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Do you want to continue buying tickets? Y: Yes, N: No");
continueBuy = sc.next().equalsIgnoreCase("Y");
}
sc.close();
}
}
+74
View File
@@ -0,0 +1,74 @@
package ticket;
public class TicketSeller implements Runnable {
private int five, ten, twenty, fifty, hundred;
public TicketSeller(int five, int ten, int twenty, int fifty, int hundred) {
this.five = five;
this.ten = ten;
this.twenty = twenty;
this.fifty = fifty;
this.hundred = hundred;
}
@Override
public synchronized void run() {
String threadName = Thread.currentThread().getName();
String[] threadNameArr = threadName.split("-");
String userName = threadNameArr[0];
int payment = Integer.valueOf(threadNameArr[1]);
boolean success = false;
while (!success) {
switch (payment) {
case 5:
five++;
success = true;
break;
case 10:
if (five > 0) {
five--;
ten++;
success = true;
}
break;
case 20:
if (ten > 0 && five > 0) {
ten--;
five--;
twenty++;
success = true;
} else if (five >= 3) {
five -= 3;
twenty++;
success = true;
}
break;
case 50:
if (ten > 0 && five > 0) {
ten--;
five--;
fifty++;
success = true;
} else if (five >= 3) {
five -= 3;
fifty++;
success = true;
}
break;
default:
throw new IllegalArgumentException("Invalid payment amount!");
}
if (!success) {
System.out.println(userName + ": Unable to get change, ticket purchase failed, waiting!");
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
System.out.println(userName + ": Ticket purchase successful!");
notifyAll();
}
}
}
}