package com.th;import java.util.ArrayList;public class DataRW implements Runnable { private final ArrayList<String> datas = new ArrayList<String>(); public DataRW() {
} public void add() {
String sm = Math.random() + "";
datas.add(sm);
System.out.println("添加数据:" + sm);
} public void minus() {
if (datas.size() > 0) {
String ds = datas.get(datas.size() - 1);
System.out.println("取出数据:" + ds);
datas.remove(datas.size() - 1);
} else {
System.out.println("集合中无数据~");
}
} public void run() {
while (true) {
synchronized (this){
if (Thread.currentThread().getName().equals("Add")) {
add();
} else if (Thread.currentThread().getName().equals("Min")) {
minus();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
} public static void main(String[] args) {
Thread t1, t2;
DataRW drw = new DataRW(); t1 = new Thread(drw);
t1.setName("Add");
t2 = new Thread(drw);
t2.setName("Min"); t1.start();
t2.start();
}
}上面的代码我认为只能是添加,线程一直运行或者是减少线程一直运行,为什么有能添加,又能减少呢?

解决方案 »

  1.   


    synchronized (this){
                if (Thread.currentThread().getName().equals("Add")) {
                    add();
                } else if (Thread.currentThread().getName().equals("Min")) {
                    minus();
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                }
    只在这个部分同步,在检测你的条件是否为真的时候另一个线程就有可能执行
      

  2.   


        public synchronized  void run() {
            while (true) {
                {
                if (Thread.currentThread().getName().equals("Add")) {
                    add();
                } else if (Thread.currentThread().getName().equals("Min")) {
                    minus();
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                }
            }
        }这样,你再试试