对于线程并发的数据同步,JAVA提供了synchronized供选择。加了synchronized方法或者代码块儿,如果一个线程进入synchronized,那么这个线程获得对应对象的锁,其他线程只能等待获取这个对象的锁。
对于线程中锁,最重要的两点是确定锁的对象是谁,谁持有了锁。
我相信上面的理解应该没有错吧,那么对于下面的代码有一些疑问,伪代码:
public class TestThread implements Runnable {
public static Object o1 = new Long(-1);
public static Object o2 = new Long(-2);
@Override
public void run() {
synchronized (o1) {
System.out.println("I am o1:" + Thread.currentThread().getName());
}
synchronized (o2) {
System.out.println("I am o2:" + Thread.currentThread().getName());
}
}
}
static ExecutorService executorService = Executors.newFixedThreadPool(3);
public static void main(String[] args) {
executorService.submit(new TestThread());
executorService.submit(new TestThread());
executorService.submit(new TestThread());
executorService.shutdown();
}
现在创建了三个线程,每个线程执行到synchronized后,其他线程都要等待。我的问题是:
是阻塞,以为是static修饰的变量,去掉static就是并行允许
public class TestThread implements Runnable {
public static Object o1 = new Long(-1);
public static Integer num = new Integer(0);
static ExecutorService executorService = Executors.newFixedThreadPool(3);
public void run() {
synchronized (o1) {
num++ ;
System.out.println("I am :" + num+"======"+Thread.currentThread().getName());
}
}
public static void main(String[] args) {
for(int i = 0 ; i < 10 ; i++){
executorService.submit(new TestThread());
}
executorService.shutdown();
}
}
运行结果:
I am :1======pool-1-thread-1
I am :2======pool-1-thread-1
I am :3======pool-1-thread-3
I am :4======pool-1-thread-3
I am :5======pool-1-thread-2
I am :6======pool-1-thread-3
I am :7======pool-1-thread-1
I am :8======pool-1-thread-3
I am :9======pool-1-thread-1
I am :10======pool-1-thread-2
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。