我同步了下面的代码,但是会导致并发问题。
我知道这是由多线程引起的,我被synchronized
关键字弄糊涂了。我预计list.length
值为 100。我该如何解决?
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class ThreadA extends Thread {
private static byte[] lock = new byte[0];
private static final List<String> list = new ArrayList<String>();
@Override
public void run() {
System.out.println(list.size());
synchronized(lock) {
int size = list.size();
if( size == 0 ) return;
if(size >= 100) {
list.clear();
}
}
}
public void add(String s) {
list.add(s);
}
public static void main(String[] args) {
for(int i = 0; i < 100; i++) {
new ThreadA().start();
new Thread(new Runnable() {
@Override
public void run() {
synchronized(lock) {
for(int m = 0; m < 100; m++) {
list.add(new Date().toLocaleString());
}
}
}
}).start();
}
System.out.println("LIST.SIZE:" + list.size());
}
}