这是一条关于假设有火车票100张,创建10个线程模拟10个售票点的,每个售票点每个售票点100毫秒卖一张票的问题。在打印出售票过程中,注意使用synchronized确保同一张票只能卖出一次。
时间: 2024-02-22 16:55:07 浏览: 23
好的,这是一个经典的多线程并发编程问题,可以使用Java中的synchronized关键字来保证线程安全。下面是示例代码:
```java
public class TicketSeller implements Runnable {
private static int ticketCount = 100; // 票数
private static Object lock = new Object(); // 锁对象
private String sellerName;
public TicketSeller(String sellerName) {
this.sellerName = sellerName;
}
@Override
public void run() {
while (ticketCount > 0) {
synchronized (lock) {
if (ticketCount > 0) {
System.out.println(sellerName + "售出第" + ticketCount + "张票");
ticketCount--;
}
}
try {
Thread.sleep(100); // 模拟售票过程,每个售票点每100毫秒卖一张票
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Main {
public static void main(String[] args) {
// 创建10个售票点
for (int i = 1; i <= 10; i++) {
new Thread(new TicketSeller("售票点" + i)).start();
}
}
}
```
在这个示例中,我们通过使用静态的同步锁对象lock来保证同一时间只有一个线程可以进入临界区(即售票过程),从而避免了线程安全问题。而每个线程的售票过程通过sleep方法来模拟,每个售票点每100毫秒卖一张票。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)