public class TestThread extends Thread {
public static int n = 0;
static synchronized void inc(){
n++;
}
public void run(){
for (int i=0;i<10 ;i++ ) {
try{
inc();
sleep(3);
}catch (Exception e) {
}
}
}
public static void main(String[] args) throws Exception {
Thread thred[] = new Thread[100];
for (int i=0;i<thred.length ;i++ ) {
thred[i] = new TestThread();
}
for (int i=0;i<thred.length ;i++ ) {
thred[i].start();
}
System.out.println(n);
}
}
上面那段代码为什么值不是1000;我已经给inc()方法加了synchronized 同步的嘛
------解决方案--------------------
package testString;
public class TestThread extends Thread {
public static int n = 0;
static synchronized void inc(){
n++;
}
public void run(){
for (int i=0;i<10 ;i++ ) {
try{
inc();
//sleep(3); //这里去掉
}catch (Exception e) {
}
}
}
public static void main(String[] args) throws Exception {
Thread thred[] = new Thread[100];
for (int i=0;i<thred.length ;i++ ) {
thred[i] = new TestThread();
}
for (int i=0;i<thred.length ;i++ ) {
thred[i].start();
}
sleep(30);//你在这里加个sleep(30);
System.out.println(n);
}
}
然后你就可以算出是1000了没有错的!为什么会这样呢?因为多线程是独立出去的线程.与MAIN线程无关了!它们与MAIN线程是平等的!你这里的原因是你main线程已经结束了!你拿到的只是MAIN线程结束那一刻的值!并不是所有程序结束的值!也就是说别的线程还在走!没走完!再加你为别的程序加睡眠!所以别的线程跑的更慢了!
------解决方案--------------------
由于你打印的结果在 主线程中,而参加运算的线程是独立于主线程的,主线程结束,但是其他的线程还在继续运行,直到结束。 你这里主线程运行main函数里的代码,执行完之后,主线程就结束了,但是你开的其他线程没有结束,主线程打印的 数据n只是其他线程运行期间的结果(其他线程还没结束),而不是其他线程运行结束的结果。 如果在主线程中得到最终的n,那么就必须保证主线程在其他运行的线程都结束后,再结束。
当然也可以把n放在同步方法中打印,主线程只是负责开启其他线程。。。