Java多线程编程的常见陷阱
1、在构造函数中启动线程
我在很多代码中都看到这样的问题,在构造函数中启动一个线程,类似这样:
public class A{ public A(){ this.x=1; this.y=2; this.thread=new MyThread(); this.thread.start(); } } class A{ int x; public int getX(){ return x; } public synchronized void setX(int x) { this.x=x; } } synchronized(array[0]) { ...... array[0]=new A(); ...... } synchronized(lock) { if(isEmpty() lock.wait(); } synchronized(lock) { while(isEmpty() lock.wait(); } Map map=Collections.synchronizedMap(new HashMap()); if(!map.containsKey("a")){ map.put("a", value); } Map map = Collections.synchronizedMap(new HashMap()); synchronized (map) { if (!map.containsKey("a")) { map.put("a", value); } } private volatile boolean stopped; public void close(){ stopped=true; } public void run(){ while(!stopped){ //do something } } private volatile IoBufferAllocator instance; public IoBufferAllocator getInsntace(){ if(instance==null){ synchronized (IoBufferAllocator.class) { if(instance==null) instance=new IoBufferAllocator(); } } return instance; } public class CheesyCounter { private volatile int value; public int getValue() { return value; } public synchronized int increment() { return value++; } } public class CheesyCounter { private volatile int value; public int getValue() { return value; } public int increment() { return value++; } } public class NumberRange { private volatile int lower, upper; public int getLower() { return lower; } public int getUpper() { return upper; } public void setLower(int value) { if (value > upper) throw new IllegalArgumentException(); lower = value; } public void setUpper(int value) { if (value < lower) throw new IllegalArgumentException(); upper = value; } } public class NumberRange { private volatile int lower, upper; public int getLower() { return lower; } public int getUpper() { return upper; } public synchronized void setLower(int value) { if (value > upper) throw new IllegalArgumentException(); lower = value; } public synchronized void setUpper(int value) { if (value < lower) throw new IllegalArgumentException(); upper = value; } }