首页 > JAVA中synchronized的疑问?

JAVA中synchronized的疑问?

对于线程并发的数据同步,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后,其他线程都要等待。我的问题是:
1. 创建了三个线程,每个线程中o1、o2都是不同的对象。根据我的理解,线程获取到的都是不同对象的锁,因此线程执行到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


public static Object o1 = new Long(-1);
public static Object o2 = new Long(-2);

注意定义中的 static

【热门文章】
【热门文章】