我使用以下代码在线程中实现同步
package pkg.com.thread1;
public class Demo4 {
/**
* @param args
*/
private static int count = 1;
public synchronized static void increment()
{
count++;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 1; i <= 10000; i++)
{
increment();
}
// TODO Auto-generated method stub
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 1; i <= 10000; i++)
{
increment();
}
// TODO Auto-generated method stub
}
});
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Count is : "+count);
}
}
每次我运行代码时,我都会得到不同的输出。 任何人都可以帮忙吗?我错过了什么吗?
答案 0 :(得分:0)
而不是Synchronized方法over Count变量将count变量声明为Atomic Integer,如下所示。import java.util.concurrent.atomic.AtomicInteger;
。它会解决你的问题。不要忘记包含{{1}}