Discuss / Java / 上厕所问题

上厕所问题

Topic source

su

#1 Created at ... [Delete] [Delete and Lock User]

若只有两个厕所,一群人来上厕所。

package semaphore;

import java.util.Random;
import java.util.UUID;
import java.util.concurrent.Semaphore;

public class SemaphoreTest {
    // 有两个厕所    final Semaphore semaphore = new Semaphore(2);

    public void access() throws InterruptedException {
        semaphore.acquire();
        try {
            // 上厕所时间            
            Random random = new Random();
            int time = random.nextInt(1000 - 300 + 1) + 300;
            Thread.sleep(time);
            String access = UUID.randomUUID().toString();
            String format = String.format("%s获取到了uuid,为%s,正在上厕所", Thread.currentThread().getName(), access);
            System.out.println(format);
        } finally {
            semaphore.release();
            System.out.println("冲马桶,释放厕所");
        }
    }

    public static void main(String[] args) throws InterruptedException {
        SemaphoreTest semaphoreTest = new SemaphoreTest();
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                try {
                    semaphoreTest.access();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

            }).start();
        }
    }
}

su

#2 Created at ... [Delete] [Delete and Lock User]

使用tryAcquire指定等待时间,是谁等厕所过程中被人抢先一步

semaphore.tryAcquire(5, TimeUnit.SECONDS)

  • 1

Reply