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好了了,就这样!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值