volatile關鍵字相信了解Java多線程的讀者都很清楚它的作用
package mythread;
public class JoinThread extends Thread
{
public static volatile int n =
public void run()
{
for (int i =
try
{
n = n +
sleep(
}
catch (Exception e)
{
}
}
public static void main(String[] args) throws Exception
{
Thread threads[] = new Thread[
for (int i =
// 建立
threads[i] = new JoinThread();
for (int i =
// 運行剛才建立的
threads[i]
for (int i =
//
threads[i]
System
}
}
如果對n的操作是原子級別的
n = n +
n++;
如果要想使這種情況變成原子操作
package mythread;
public class JoinThread extends Thread
{
public static int n =
public static synchronized void inc()
{
n++;
}
public void run()
{
for (int i =
try
{
inc(); // n = n +
sleep(
}
catch (Exception e)
{
}
}
public static void main(String[] args) throws Exception
{
Thread threads[] = new Thread[
for (int i =
// 建立
threads[i] = new JoinThread();
for (int i =
// 運行剛才建立的
threads[i]
for (int i =
//
threads[i]
System
}
}
上面的代碼將n=n+
From:http://tw.wingwit.com/Article/program/Java/gj/201311/27293.html