- package exercises;
- import java.lang.reflect.Method;
- import java.util.HashMap;
- import java.util.Iterator;
- import java.util.Map;
- import java.util.Set;
- import java.util.TreeMap;
- public class Test {
- public static void main(String[] args) throws Exception {
- // reflectMap();
- // mapDemo();
- Res res = new Res();
- new Thread() {
- @Override
- public void run() {
- while (true) {
- try {
- Thread.sleep(500);
- res.put();
- } catch (InterruptedException e) {
- }
- }
- }
- }.start();
-
- new Thread() {
- @Override
- public void run() {
- while (true) {
- try {
- Thread.sleep(500);
- res.out();
- } catch (InterruptedException e) {
- }
- }
- }
- }.start();
- }
- private static void reflectMap() throws Exception {
- Map<Integer, Integer> map = new HashMap<Integer, Integer>();
- map.put(5, 23);
- System.out.println(map);
- Method methodPut = map.getClass().getMethod("put", Object.class,
- Object.class);
- methodPut.invoke(map, "abc", "bcd");
- System.out.println(map);
- }
- private static void mapDemo() {
- Map<String, Integer> map = new TreeMap<String, Integer>();
- map.put("abc", 123);
- map.put("bcd", 234);
- map.put("cde", 345);
- map.put("def", 456);
- // 1
- Set<String> set = map.keySet();
- Iterator<String> it = set.iterator();
- while (it.hasNext()) {
- String key = it.next();
- int value = map.get(key);
- System.out.println(key + ":" + value);
- }
- // 2
- Set<Map.Entry<String, Integer>> entrySet = map.entrySet();
- Iterator<Map.Entry<String, Integer>> entryIt = entrySet.iterator();
- while (entryIt.hasNext()) {
- Map.Entry<String, Integer> me = entryIt.next();
- String key = me.getKey();
- int value = me.getValue();
- System.out.println(key + ":" + value);
- }
- }
- }
- /**
- * 起两个线程,操作共享数组,隔一段时间向里面添加数据
- *
- * @author always
- *
- */
- class Res {
- private String name;
- private String sex;
- private boolean isFull = false;
- public boolean flag = false;
- public synchronized void put() throws InterruptedException {
- if (isFull)
- wait();
- if (flag) {
- name = "zhangsan";
- sex = "nan";
- } else {
- name = "李四";
- sex = "女";
- }
- flag = flag ? false : true;
- isFull = true;
- notify();
- }
- public synchronized void out() throws InterruptedException {
- if (!isFull)
- wait();
- System.out.println(name + " :: " + sex);
- isFull = false;
- notify();
- }
- }
复制代码 |