一个展现java多线程原理的例子

来源:互联网 发布:淘宝显示不是私密连接 编辑:程序博客网 时间:2024/05/17 03:19

这个例子很好的体现出了多线程之间的竞争,同时,main方法也是一个线程,并且也无法确定到底哪个线程先执行,哪个线程后执行,如果需要确定先后顺序的话,只能加同步线程锁了。

    static int j = 1;    static int k = 0;    public static void main(String[] args) {        System.out.println("Main thread started");        for(int i =0;i<1000;i++){          k=i;            new Thread(new Runnable() {                @Override                public void run() {                  System.out.println("this is the "+ k +" thread");                  j++;                }              }).start();        }        System.out.println("Main thread end");     }
1 0