转--秒杀多线程第四篇 一个经典的多线程同步问题(续)

demo in java:

package com.multithread.main.sampleExample;



import com.multithread.main.ExampleInterface;



public class SampleExample extends ExampleInterface{



    final int MAX_THREAD_NUM = 10;

    int g_num = 0;

    @Override

    public void startDemo() {

        int i=0;

        while(i<MAX_THREAD_NUM)

        {

            Thread t = new SampleMultiThread(i);

            t.start();

            i++;

        }

    }

    

    

    class SampleMultiThread extends Thread{



        int index = -1;

        public SampleMultiThread(int index)

        {

            this.index = index;            

        }

        

        @Override

        public void run() {

            // TODO Auto-generated method stub

            g_num++;

            System.out.println("g_num is:"+g_num +"\t"+"index is:"+this.index);

        }

        

        

        

    }



}

result:

g_num is:2    index is:0
g_num is:8    index is:6
g_num is:7    index is:9
g_num is:6    index is:7
g_num is:5    index is:5
g_num is:4    index is:3
g_num is:3    index is:2
g_num is:2    index is:1
g_num is:10    index is:8
g_num is:10    index is:4

你可能感兴趣的:(线程同步)