標籤:線程 blocking title over adt function lis str locking
以下代碼 不考慮多伺服器
限制線程池的大小 和隊列的限制來實現
package org.zhang;import java.util.concurrent.BlockingQueue;import java.util.concurrent.Executors;import java.util.concurrent.SynchronousQueue;import java.util.concurrent.ThreadPoolExecutor;import java.util.concurrent.TimeUnit;/** * 單伺服器用線程池實現秒殺的思路一 * * @author zhanghaijun * */public class ExecutorsTest {public static boolean flag = true; // 秒殺物品的標記public static void main(String[] args) {ThreadPoolExecutor pool = new ThreadPoolExecutor(1, 1, 0L,TimeUnit.MILLISECONDS, new SynchronousQueue<Runnable>());ThreadTest t1 = new ThreadTest("張三");ThreadTest t2 = new ThreadTest("李四");ThreadTest t3 = new ThreadTest("王五");try {pool.execute(t1);} catch (Exception e) {System.out.println(t1.getUserName() + "沒有搶到");}try {pool.execute(t3);} catch (Exception e) {System.out.println(t3.getUserName() + "沒有搶到");}try {pool.execute(t2);} catch (Exception e) {System.out.println(t2.getUserName() + "沒有搶到");}pool.shutdown();}}class ThreadTest extends Thread {private String userName;public ThreadTest(String userName) {super();this.userName = userName;}@Overridepublic void run() {try {Thread.sleep(200);if (ExecutorsTest.flag) {System.out.println(this.userName + "秒殺成功");ExecutorsTest.flag = false;}} catch (InterruptedException e) {e.printStackTrace();}}public String getUserName() {return userName;}public void setUserName(String userName) {this.userName = userName;}}
java 簡單秒殺