并发的知识点是面试的常问技术,比如线程池创建的参数有哪些?写一段模拟抢票的代码等等。
这里我们来说说模拟抢票的代码。
代码:
package com.example;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @author XuYangWei
* @Description:
* @Date 2021/4/14 16:21
*/
public class ExecutorTest {
//票数
static int count = 5;
private static Runnable getThread(final int i) {
return new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
if(count>0){
System.out.println("用户" + i + "抢到了第" + count + "张票");
count--;
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
}
public static void main(String args[]) {
ExecutorService cachePool = Executors.newCachedThreadPool();
for (int i = 1; i <= 10; i++) {
cachePool.execute(getThread(i));
}
}
}