编辑代码

// import java.util.concurrent.locks.ReentrantLock;

// public class FairLockExample {
//     private final ReentrantLock lock = new ReentrantLock(true); // true 表示公平锁

//     public void doSomething() {
//         lock.lock();
//         try {
//             // 执行一些操作
//             System.out.println("Task executed by: " + Thread.currentThread().getName());
//         } finally {
//             lock.unlock();
//         }
//     }

//     public static void main(String[] args) {
//         FairLockExample example = new FairLockExample();

//         for (int i = 0; i < 10; i++) {
//             new Thread(() -> example.doSomething()).start();
//         }
//     }
// }

// import java.util.concurrent.locks.ReentrantLock;

// public class NonFairLockExample {
//     private final ReentrantLock lock = new ReentrantLock(false); // false 表示非公平锁

//     public void doSomething() {
//         lock.lock();
//         try {
//             // 执行一些操作
//             System.out.println("Task executed by: " + Thread.currentThread().getName());
//         } finally {
//             lock.unlock();
//         }
//     }

//     public static void main(String[] args) {
//         NonFairLockExample example = new NonFairLockExample();

//         for (int i = 0; i < 20; i++) {
//             new Thread(() -> example.doSomething()).start();
//         }
//     }
// }

// import java.util.concurrent.ExecutorService;
// import java.util.concurrent.Executors;

// public class ThreadPoolExample {
//     public static void main(String[] args) {
//         ExecutorService executor = Executors.newFixedThreadPool(5);

//         for (int i = 0; i < 30000; i++) {
//             executor.submit(() -> {
//                 System.out.println("Task executed by: " + Thread.currentThread().getName());
//             });
//         }

//         executor.shutdown(); // 关闭线程池
//     }
// }