当前位置: 技术问答>java相关
线程同步有问题吗?
来源: 互联网 发布时间:2015-01-06
本文导语: 我写了一个线程同步的测试程序。但发现结果不稳定,有时结果会不同步。我的环境是 athlon 900, win2000, jdk1.1.6 在p133, win95, jdk1.3上结果正确。为什么? 程序见下: class Syn { private int count = 0; public synchron...
我写了一个线程同步的测试程序。但发现结果不稳定,有时结果会不同步。我的环境是
athlon 900, win2000, jdk1.1.6
在p133, win95, jdk1.3上结果正确。为什么?
程序见下:
class Syn {
private int count = 0;
public synchronized void inc() {
count++;
count++;
System.out.print("+");
count--;
count--;
}
public int getCount() {
return count;
}
}
public class SimpleThread extends Thread {
private int no = 0;
private Syn s = null;
private int count = 0;
public SimpleThread(int number, Syn syn) {
no = number;
s = syn;
System.out.println("Making thread" + no);
}
public void run() {
while(true) {
s.inc();
if (s.getCount() != 0)
System.out.println("Not equal zero!");
if(count++ > 50) return;
try {
sleep(100);
} catch(Exception e) {}
}
}
public static void main(String[] args) {
Syn ss = new Syn();
for (int i = 1; i 50) return;
try {
sleep(100);
} catch(Exception e) {}
} // 同步结束
}
}
public static void main(String[] args) {
Syn ss = new Syn();
for (int i = 1; i
athlon 900, win2000, jdk1.1.6
在p133, win95, jdk1.3上结果正确。为什么?
程序见下:
class Syn {
private int count = 0;
public synchronized void inc() {
count++;
count++;
System.out.print("+");
count--;
count--;
}
public int getCount() {
return count;
}
}
public class SimpleThread extends Thread {
private int no = 0;
private Syn s = null;
private int count = 0;
public SimpleThread(int number, Syn syn) {
no = number;
s = syn;
System.out.println("Making thread" + no);
}
public void run() {
while(true) {
s.inc();
if (s.getCount() != 0)
System.out.println("Not equal zero!");
if(count++ > 50) return;
try {
sleep(100);
} catch(Exception e) {}
}
}
public static void main(String[] args) {
Syn ss = new Syn();
for (int i = 1; i 50) return;
try {
sleep(100);
} catch(Exception e) {}
} // 同步结束
}
}
public static void main(String[] args) {
Syn ss = new Syn();
for (int i = 1; i