Skip to content

Instantly share code, notes, and snippets.

@royguo
Created July 16, 2013 08:16
Show Gist options
  • Save royguo/6006800 to your computer and use it in GitHub Desktop.
Save royguo/6006800 to your computer and use it in GitHub Desktop.
双Buffer切换的一个Java小实验
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class BufferTest {
private static volatile List<String> list = new ArrayList<String>();
public static void init() {
for (int i = 0; i < 10; i++) {
list.add(i + " " + i);
}
}
public static void switchList() {
List<String> list2 = new ArrayList<String>();
for (int i = 3; i < 7; i++) {
list2.add(i + " " + i);
}
list = list2;
System.out.println("new list.size() = " + list.size());
}
public static void readList() throws Exception {
int count = 0;
// foreach使用的是iterator,开始循环时已经确定堆内存的地址,中间更换不影响其遍历原有数组
// for (String s : list) {
// Thread.sleep(1000);
// System.out.println(s + " list.size() = " + list.size());
// count++;
// }
// Iterator获得数组的地址之后,与原数组就没有关系了,原数组引用变了循环依然遍历的是原数组.
Iterator<String> i = list.iterator();
while (i.hasNext()) {
Thread.sleep(1000);
System.out.println(i.next() + " list.size() = " + list.size());
}
// 直接for循环使用list.get每次调用都可能切换到新的list上,加上volatile可以保证可见性.
// for (int i = 0; i < list.size(); i++) {
// Thread.sleep(1000);
// System.out.println(list.get(i));
// count++;
// }
System.out.println("elements count = " + count);
}
public static void main(String[] args) throws Exception {
init();
new Thread(new Runnable() {
public void run() {
System.out.println("start thead 1");
try {
readList();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("end thead 1");
}
}).start();
Thread.sleep(5000);
new Thread(new Runnable() {
public void run() {
System.out.println("start thead 2");
try {
System.out.println("begin to switch ...");
switchList();
System.out.println("switch finished ! ");
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("end thead 2");
}
}).start();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment