import java.util.concurrent.Callable;

class TicketSeller implements Callable { private static int ticketCount = 100; // 总票数,假设有100张票

@Override
public Integer call() {
    int count = 0;
    while (ticketCount > 0) {
        synchronized (TicketSeller.class) {
            if (ticketCount > 0) {
                System.out.println(Thread.currentThread().getName() + "卖出了第" + ticketCount + "张票");
                ticketCount--;
                count++;
            }
        }
        try {
            Thread.sleep(100); // 模拟卖票过程中的一些其他操作
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    return count;
}

public static void main(String[] args) throws ExecutionException, InterruptedException {
    TicketSeller seller1 = new TicketSeller();
    TicketSeller seller2 = new TicketSeller();
    TicketSeller seller3 = new TicketSeller();

    ExecutorService executorService = Executors.newFixedThreadPool(3);
    Future<Integer> result1 = executorService.submit(seller1);
    Future<Integer> result2 = executorService.submit(seller2);
    Future<Integer> result3 = executorService.submit(seller3);

    System.out.println("卖出的票数:" + (result1.get() + result2.get() + result3.get()));
    executorService.shutdown();
}

} 改造为实现Callable接口并实现call方法后,可以通过ExecutorService的submit方法提交任务,并通过Future对象获取线程的返回值。通过使用Callable接口可以更好地控制并发任务的执行,可以获取每个线程的返回结果,并进行进一步的处理。另外,使用Callable接口可以更灵活地控制线程池的大小和任务的执行方式,可以提高程序的效率和性能

将这段代码改造为实现Callable接口并实现call方法。实现并说明有什么不同。class TicketSeller extends Thread private static int ticketCount = 100; 总票数假设有100张票 Override public void run while ticketCou

原文地址: https://www.cveoy.top/t/topic/ir2W 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录