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