比较代码一与代码二,代码一是在main方法中开了1000个线程,此时我加了锁不会有线程问题。假如代码二是放在controller中执行,此时有1000个用户请求进来,是不是也是相当于开了1000个线程去执行inc方法,还是说这1000个请求就与java中的多线程没有一点关系,是怎么解释这1000个请求?
代码一:
public class LockExample {
static Lock lock = new ReentrantLock();
private static int count = 0;
public static void inc(){
lock.lock();//抢占锁,如果没有抢占到锁,会阻塞
// lock.tryLock()//如果没有抢占到锁,这里不会阻塞
try {
Thread.sleep(1);
count++;
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
public static void main(String[] args) throws InterruptedException {
for(int i = 0; i < 1000; i++){
new Thread(()->LockExample.inc()).start();
}
Thread.sleep(3000);
System.out.println("result:"+count);
}
}
代码二:
public class LockExample {
static Lock lock = new ReentrantLock();
private static int count = 0;
public static void inc(){
try {
Thread.sleep(1);
count++;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}