天天看点

Java线程及同步(synchronized)样例代码

Java线程及同步(synchronized)样例代码

import java.io.*;

import java.util.*;

import java.text.SimpleDateFormat;

public class TestThread extends Thread

{

    private static Integer threadCounterLock; //用于同步,防止数据被写乱

    private static int threadCount; //本类的线程计数器

    static

    {

        threadCount = 0;

        threadCounterLock = new Integer(0);

    }

    public TestThread()

    {

        super();

    }

    public synchronized static void incThreadCount()

    {

        threadCount++;

        System.out.println("thread count after enter: " + threadCount);

    }

    public synchronized static void decThreadCount()

    {

        threadCount--;

        System.out.println("thread count after leave: " + threadCount);

    }

    public void run()

    {

        synchronized(threadCounterLock) //同步

        {

            threadCount++;

            System.out.println("thread count after enter: " + threadCount);

        }

        //incThreadCount(); //和上面的语句块是等价的

        final long nSleepMilliSecs = 1000;  //循环中的休眠时间

        long nCurrentTime = System.currentTimeMillis();

        long nEndTime = nCurrentTime + 30000;  //运行截止时间

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        try

        {

            while (nCurrentTime < nEndTime)

            {

                nCurrentTime = System.currentTimeMillis();

                System.out.println("Thread " + this.hashCode() + ", current time: " + simpleDateFormat.format(new Date(nCurrentTime)));

                try

                {

                    sleep(nSleepMilliSecs);

                }

                catch(InterruptedException ex)

                {

                    ex.printStackTrace();

                }

            }

        }

        finally

        {

            synchronized(threadCounterLock) //同步

            {

                threadCount--;

                System.out.println("thread count after leave: " + threadCount);

            }

            //decThreadCount();   //和上面的语句块是等价的

        }

    }

    public static void main(String[] args)

    {

        TestThread[] testThread = new TestThread[2];

        for (int i=0; i<testThread.length; i++)

        {

            testThread[i] = new TestThread();

            testThread[i].start();

        }

    }

}

同步就是简单的说我用的时候你不能用,大家用的要是一样的就这样!

比如说有只苹果很好吃,我拉起来咬一口,放下,你再拉起咬一口,这就同步了,要是大家一起咬,呵呵,那就结婚吧,婚礼上常能看到这个,也不怕咬着嘴,嘻嘻嘻!

举个例子,现在有个类,类中有一个私有成员一个苹果,两个方法一个看,一个吃。

现在不同步,我一“看”,哈哈一个苹果,我“吃”四分之一了

你一“看”,哈哈一个苹果,也“吃”四分之一了。

可能的情况就是都是看到一个苹果但我的吃方法用在你的之前,所以可能你只能吃到3/4的1/4也就是3/16个而不是1/4个苹果了。

现在加入同步锁,我在吃的时候你看被锁,等吃完了,你再看,啊3/4个苹果,吃1/3好了了,就这样!