Java 并发问题 - 锁定和同步方法

Java concurrency issue - Locks and Synchronize method

我正在研究可重入锁并试图将其与 Synchronize 相关联。然而,这两个 类 都给了我意想不到的结果。我希望 arrayList 有 0 到 9。但是这两个程序都没有这个值。请建议。 带锁:

package Threads;

import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Locking {

    Lock lock = new ReentrantLock(true);
    ArrayList<Integer> al = new ArrayList<Integer>();
    static int count = 0;

    public void producer() {
        lock.lock();
        count++;
        al.add(count);
        System.out.println(al);
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        // System.out.println("I came out of this block:"+Thread.currentThread().getName());
    }

    public void consumer() {
    }

    public static void main(String[] args) {
        // ExecutorService ex= Executors.newCachedThreadPool();
        ExecutorService ex = Executors.newFixedThreadPool(10);

        for (int i = 0; i < 10; i++) {
            ex.submit(new Runnable() {

                @Override
                public void run() {
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    new Locking().producer();
                }

            });
        }
        ex.shutdown();
    }
}

同步:

package Threads;

import java.util.ArrayList;
import java.util.Collections;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class LockwithSynchronize {

    ArrayList<Integer> al = new ArrayList<Integer>();
    static int count = 0;

    public synchronized void producer() {
        count++;
        al.add(count);
        System.out.println(al);
        try {
            Thread.sleep(5000);
            // System.out.println("I came out of this block:"+Thread.currentThread().getName());
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        // ExecutorService ex= Executors.newCachedThreadPool();
        ExecutorService ex = Executors.newFixedThreadPool(10);

        for (int i = 0; i < 10; i++) {
            ex.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    new LockwithSynchronize().producer();
                }
            });
        }
        ex.shutdown();
    }

}

您的 synchronize 不保护静态变量 - synchonize 在这样使用时仅锁定当前 this 对象的监视器。任何 produce() 调用都不会等待您发布的代码中的任何其他调用。锁定共享的内容 - 例如 LockWithProducer.class。

这有很多问题。

首先,您期望它包含 0..9,但是您在 al.add(count) 之前调用了 count++,这意味着您实际上应该期望 1..10.

由于您每次都使用新的 LockWithSynchronizeLocking,因此实际上没有任何共享锁——每个实例都有自己的锁,不会与任何其他锁冲突,这意味着您的 count 变量完全不受保护。而且您可能会定期收到损坏的 ArrayList,因为 add 在没有同步的情况下在多个线程上被调用,或者 ConcurrentModificationException 或类似的。

试试这个:

public static void main(String [] args){

    ExecutorService ex= Executors.newFixedThreadPool(10);

    final Locking producer = new Locking();

    for (int i=0; i<10;i++)
    {
        ex.submit(new Runnable(){

            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                producer.producer();
            }

        });
    }

    ex.shutdown();
}

请注意,我们不是每次都使用新的 Locking,而是重复使用同一个实例,现在您期望的情况发生了:您很快生成了 10 个线程,每个线程等待两秒钟再尝试打电话给 producer()。一个线程获得锁,而其他九个线程阻塞。获得锁的线程在退出前等待五秒钟,此时下一个线程获得锁,等待五秒钟,然后退出,等等。所以这将花费将近一分钟 运行.

类似的修改也修复了另一个。