以下就是一段用线程搞死Vector的例子。虽然这么用Vector有些近乎变态,但是足以说明线程安全不是用synchronized同步每个函数就可以解决的。import java.util.*;public class Dead { private Vector v = new Vector(); private boolean running;
public void start() { T1 t1 = new T1(); T2 t2 = new T2(); running = true; t1.start(); t2.start(); System.out.println("Started"); }
public void stop() { running = false; System.out.println("Stoped"); }
class T1 extends Thread { public void run() { while (running) { v.add(new Integer(5)); int i = v.size(); try { sleep(20); } catch (Exception e) { } System.out.println(v.get(i - 1)); } } }
class T2 extends Thread { public void run() { while (running) { v.removeAllElements(); } } }
public static void main(String[] args) { Dead d = new Dead(); d.start(); try { Thread.sleep(5000); } catch (Exception e) {
有关线程安全的一些比较好的讨论文章,你可以去IBM的网站上查看。
private Vector v = new Vector();
private boolean running;
public void start() {
T1 t1 = new T1();
T2 t2 = new T2();
running = true;
t1.start();
t2.start();
System.out.println("Started");
}
public void stop() {
running = false;
System.out.println("Stoped");
}
class T1 extends Thread {
public void run() {
while (running) {
v.add(new Integer(5));
int i = v.size();
try {
sleep(20);
} catch (Exception e) {
}
System.out.println(v.get(i - 1));
}
}
}
class T2 extends Thread {
public void run() {
while (running) {
v.removeAllElements();
}
}
}
public static void main(String[] args) {
Dead d = new Dead();
d.start();
try {
Thread.sleep(5000);
} catch (Exception e) {
}
d.stop();
}
}