package cn.pra.curr;
public class TestPro {
public static void main(String[] args) {
Exce e1 = new Exce(new Test("a")); // 修改数据时将字符串换成修改数据的唯一标识
Exce e2 = new Exce(new Test("a2"));
Exce e3 = new Exce(new Test("a3"));
Exce e4 = new Exce(new Test("a4"));
Exce e5 = new Exce(new Test("a5"));
Exce e6 = new Exce(new Test("a6"));
Exce e7 = new Exce(new Test("a"));
Exce e8 = new Exce(new Test("a"));
Exce e9 = new Exce(new Test("a"));
Thread t1 = new Thread(e1, "t1");
Thread t2 = new Thread(e2, "t2");
Thread t3 = new Thread(e3, "t3");
Thread t4 = new Thread(e4, "t4");
Thread t5 = new Thread(e5, "t5");
Thread t6 = new Thread(e6, "t6");
Thread t7 = new Thread(e7, "t7");
Thread t8 = new Thread(e8, "t8");
Thread t9 = new Thread(e9, "t9");
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
t6.start();
t7.start();
t8.start();
t9.start();
}
}
class Test {
public String str;
public Test(String str) {
this.str = str;
}
public synchronized void write(String u) {
synchronized (u.intern()) {
// do something
try {
Thread.sleep(3000);
System.out.println(Thread.currentThread().getName() + ":" + u);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class Exce implements Runnable {
private Test test;
public Exce(Test test) {
this.test = test;
}
@Override
public void run() {
test.write(test.str);
}
}
运行结果:前面6个几乎同时出来,后面3个,每隔3s出现一个
t3:a3
t4:a4
t2:a2
t1:a
t6:a6
t5:a5
t9:a
t8:a
t7:a