Java多线程顺序执行
上一篇 /
下一篇 2012-07-12 13:18:53
/ 个人分类:Java
51Testing软件测试网,}p1K"f3y}sz%u b 可恶的Java多线程,一直没搞懂同步的作用!
2g)`&Wc^?"U2^et}$^051Testing软件测试网,sH:AY^9D 一直以为同步的时候只要锁住对象就能顺序执行了:
E#sy J,ERa2_.^;`051Testing软件测试网T*P`:Z b ~
a$} O;b'I public classTest{ OZ#y)e4{`~&E0 final static byte[] b = new byte[0];51Testing软件测试网\
h%P6N9c4^|S9ce~ 51Testing软件测试网T
^J e`1Gk*BT public static void main(String[] args) {51Testing软件测试网N*U,k'~+F?u Test t = new Test();51Testing软件测试网p-[;a(z-f8Gh t.thread.start(); h.v l,T%J*XD"K[0 Test t2 = new Test();51Testing软件测试网SdS$}Z*F u`'\ t2.thread.start(); ?Q!ld
d-wT1{0 }51Testing软件测试网]I)Fk0U NpR 51Testing软件测试网C%a8kL2D&l7}5e{ Thread thread = new Thread(new Runnable() {51Testing软件测试网e,O%cr9u @Override c!X;y$a/\ `*B0 public void run() {51Testing软件测试网4u;y
h ^]2K;P test();51Testing软件测试网+HD7G/ct ~A } am%B{%\#t0 });51Testing软件测试网;jsXb3~B
w!Jg5G 51Testing软件测试网pc:FL B
N+b j+g public void test() { RD&A0F)@[qK;OX0 synchronized (this) {51Testing软件测试网 DPc#M BGYfi for (int n = 0; n < 100; n++) { k&xT#_ z`0 System.out.println(thread.getName() + ":" + n);51Testing软件测试网b H&AY!l'^ try { 8i^H.`"~"^,kB0 Thread.sleep(1000);51Testing软件测试网.v5B{)F-T } catch (InterruptedException e) {
|