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)等。
public <T> void sort(final Vector<T> list);
public <T> void sort(finalVector<T> list){ synchronized (list) { //perform sorting on the list. }}
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); }}