key 发表于 5-8-2009 12:16:03

一个有趣的多线程实验程序及其结果

什么也不说了,看程序,然后测试一下:import java.util.concurrent.atomic.*;
import static java.lang.System.*;

public class T1 implements Runnable {
   private static final AtomicInteger ai = new AtomicInteger();
   private static final ThreadLocal<Integer> v =
      new ThreadLocal<Integer>() {
            public Integer initialValue() {
                return ai.getAndIncrement();
            }
      };
    private static int lastValue = -1;

    public T1() {
    }

    public void run() {
      v.get(); //initialize thread local value
      doit();
    }

    private synchronized void doit() {
      int x = v.get();
      if(lastValue!=-1 && lastValue != x + 1)
            out.println("last = " + lastValue + ", cur= " + x);
      lastValue = x;

      //out.println(v.get() + ": start");
      try{ Thread.sleep(1000); } catch(InterruptedException ie){}
      //out.println(v.get() + ": stop");
    }

    public static void main(String [] args){
      Thread[] th = new Thread;
      T1 t1 = new T1();

      for(int k=0; k<th.length; ++k) {
            th = new Thread(t1);
      }

      for(int k=0; k<th.length; ++k) {
            th.start();
      }

    }
}在winxp下的某次运行结果是:$ java T1
last = 0, cur= 999
last = 999, cur= 997
last = 997, cur= 998
last = 998, cur= 996
last = 890, cur= 888
last = 888, cur= 889
last = 889, cur= 887
last = 817, cur= 814
last = 814, cur= 815
last = 815, cur= 816
last = 816, cur= 813
last = 805, cur= 802
last = 802, cur= 803
last = 803, cur= 804
last = 804, cur= 801
last = 793, cur= 791
last = 791, cur= 792
last = 792, cur= 790
last = 727, cur= 725
last = 725, cur= 726
last = 726, cur= 724
last = 672, cur= 670
last = 670, cur= 671
last = 671, cur= 669
last = 659, cur= 657
last = 657, cur= 658
last = 658, cur= 656
last = 532, cur= 530
last = 530, cur= 531
last = 531, cur= 529
last = 479, cur= 477
last = 477, cur= 478
last = 478, cur= 476
last = 398, cur= 396
last = 396, cur= 397
last = 397, cur= 395
last = 329, cur= 327
last = 327, cur= 328
last = 328, cur= 326
last = 321, cur= 319
last = 319, cur= 320
last = 320, cur= 318
last = 254, cur= 251
last = 251, cur= 252
last = 252, cur= 253
last = 253, cur= 250
last = 215, cur= 213
last = 213, cur= 214
last = 214, cur= 212
last = 201, cur= 199
last = 199, cur= 200
last = 200, cur= 198
last = 198, cur= 196
last = 196, cur= 197
last = 197, cur= 195
last = 171, cur= 169
last = 169, cur= 170
last = 170, cur= 168
last = 93, cur= 90
last = 90, cur= 92
last = 91, cur= 89
last = 63, cur= 61
last = 61, cur= 62
last = 62, cur= 60
last = 42, cur= 21
last = 21, cur= 41
last = 22, cur= 20
last = 12, cur= 1
last = 1, cur= 11本实验的结果具有随机性,但从统计的角度来看,Java在线程竞争和执行上有一定的bias
页: [1]
查看完整版本: 一个有趣的多线程实验程序及其结果