62,635
社区成员




/**
* Created by does on 17/2/15.
*/
public class Super {
public static void main(String[] args) {
Super aSuper = new Super();
Sub sub =(Sub) aSuper;
}
}
class Sub extends Super{
}
/**
* Created by does on 17/2/15.
*/
public class Test {
public static void main(String[] args) {
Test test = new Test();
try {
test.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class HashMapDemo {
public static void main(String[] args) {
final HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < 100000; i++) {
map.put(i, i);
}
for (int i = 0; i < 10; i++) {
new Thread(new Runnable() {
@Override
public void run() {
for (int j = 999; j < 1005; j++) {
System.out.println(Thread.currentThread().getName() +" " + map.remove(j));
}
}
}).start();
}
}
}
从map中删除几个数据,如果是线程安全的,只要删一次即可,但HashMap,有可能会删除数次,还是因为remove方法不是原子操作,当某个线程从map中找到了数据,但被剥夺了执行权,同时另外一个线程完成了删除,该线程恢复,继续操作,造成了数据错误。[/quote]
我也知道这样写可以.. 但是实际上这个证明是从"经验"上来推断的事实, 而不是从逻辑上来否定的.public class HashMapDemo {
public static void main(String[] args) {
final HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < 100000; i++) {
map.put(i, i);
}
for (int i = 0; i < 10; i++) {
new Thread(new Runnable() {
@Override
public void run() {
for (int j = 999; j < 1005; j++) {
System.out.println(Thread.currentThread().getName() +" " + map.remove(j));
}
}
}).start();
}
}
}
从map中删除几个数据,如果是线程安全的,只要删一次即可,但HashMap,有可能会删除数次,还是因为remove方法不是原子操作,当某个线程从map中找到了数据,但被剥夺了执行权,同时另外一个线程完成了删除,该线程恢复,继续操作,造成了数据错误。