public class ThreadTest {
static int count = 0;
public static class LargeThread extends Thread {
public LargeThread() {
}
public void run() {
change();
}
private synchronized void change(){
++count;
System.out.println(count);
}
}
public static void main(String[] args) throws InterruptedException {
while(true){
for (int i = 0; i < 500; i++) {
new LargeThread().start();
//System.out.println(count++);
}
Thread.sleep(1000);
}
}
}
1745
1746
1747
1748
1749
1953
1750
1751
1752
1753
1754
上面是输出结果, 竟然会有1953 这样的值? 同步方法无效么?
[code="java"] public synchronized static void change(){
++count;
System.out.println(count);
} [/code]
我给你改了下. 这样或许是你想要的结果.
[code="java"]public class ThreadTest {
static int count = 0;
public synchronized static void change(){
++count;
System.out.println(count);
}
public static class LargeThread extends Thread {
public LargeThread() {
}
public void run() {
ThreadTest.change();
}
// private void change(){
// synchronized(count){
// ++count;
// System.out.println(count);
// }
// }
}
public static void main(String[] args) throws InterruptedException {
while(true){
for (int i = 0; i < 500; i++) {
new LargeThread().start();
//System.out.println(count++);
}
// Thread.sleep(1000);
}
}
}
[/code]
synchronized 关键字修饰的变量或者方法,应该是在thread访问的外部定义的;
而不是在Thread内部;
因为你的change()方法,只被当前线程访问,也不存在并发问题了.
应该是使用system.out.println.打印的时候不同步而已吧.
改成
[code="java"]
private void change(){
synchronized (ThreadTest.class) {
++count;
System.out.println(count);
}
}
[/code]
因为你操作的是类变量,所以就需要给类加锁。
LZ原来的代码是给Thread对象加锁。
LS的答案也正确,不过改动较大:)