Java線程及同步(synchronized)範例代碼

來源:互聯網
上載者:User

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好了了,就這樣!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.