Java方法参数在多线程环境中的同步
JDK中java.util.Collections类提供了一些方便的操作集合的方法。例如:
public static void reverse(List<?> list)public static void shuffle(List<?> list)public static <T extends Comparable<? super T>> void sort(List<T> list)等。
这些方法都是非线程安全的。在多线程环境下,假设一个线程正在对List进行排序,如果另一个线程同时从List中删除一个元素的话,很可能会导致异常发生。
如何修改上述的方法,使之线程安全呢?
在coding之前,我们必须了解有一下几个前提:
1. 作为一个类库,我们不能预料其他开发人员如何使用该方法。即,如果其他开发人员在未加锁的环境中修改作为参数传递进来的List,即使我们简单地对该对象加锁, 也不能保护该对象。
2. 如果对整个类或者实例加锁,成本太高,同时也无法解决问题1。
因此,例如要编写一个线程安全的排序方法,首先,要排序的列表必须是线程安全的,比如List就不适合作为参数(无法确保其是synchronized的),而必须替换为Vector。即方法需要修改为:
public <T> void sort(final Vector<T> list);
其次,要保证排序操作不能被其他线程打断,即排序操作需要加锁:
public <T> void sort(finalVector<T> list){ synchronized (list) { //perform sorting on the list. }}
这两个条件缺一不可。测试代码如下 (TestSyncParam.java):
import java.util.Vector;public class TestSyncParam { public void sort(Vector<Integer> list) { synchronized (list) { System.out.println("Start bubble sorting." + Thread.currentThread()); for (int i = 0; i < list.size(); i++) { for (int j = list.size() - 1; j > i; j--) { if (list.get(j) < list.get(j - 1)) { int tmp = list.get(j - 1); list.set(j - 1, list.get(j)); list.set(j, tmp); } try { // slow down to give other threads a chance to touch 'list' Thread.sleep(50); } catch (InterruptedException e) { } } } System.out.println("Bubble sorting done." + Thread.currentThread()); }//end of sync } public static void main(String[] args) { int[] ii = new int[] { 12, 5, 18, 3, 50, 34, 4, 8, 11, 3, 25, 2 }; final Vector<Integer> list = new Vector<Integer>(); for (int i : ii) list.add(i); Runnable r1 = new Runnable() { public void run() { try { Thread.sleep(100); } catch (InterruptedException e) { } System.out.println("Trying to remove first element. - " + Thread.currentThread()); Integer i = list.remove(0); System.out.println("Removed '" + i + "', size: "+list.size()+" - " + Thread.currentThread()); } }; TestSyncParam tsp = new TestSyncParam(); new Thread(r1).start(); tsp.sort(list); }}
执行结果如下:
Start bubble sorting.Thread[main,5,main]Trying to remove first element. - Thread[Thread-1,5,main]Bubble sorting done.Thread[main,5,main]Removed '2', size: 11 - Thread[Thread-1,5,main]
总之,多线程环境下,我不建议将共享资源作为方法参数。如果必须,则该资源对象必须线程安全,方法的实现同时需要避免死锁。