日期:2014-05-20  浏览次数:20745 次

java 关于使用线程池计算加法的运算不能出正确的结果请帮助
package test2;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class T1 {
static int a;
static int b;
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(10);
T1 t = new T1();
for (int i = 0; i < 10; i++)
{
a = i;
b = i;
// 创建一个可重用固定线程数的线程池

Thread t1 = new MyThread();
// 将线程放入池中进行执行
pool.execute(t1);
}
}

static class MyThread extends Thread {
@Override
public synchronized void run() {

System.out.println(Thread.currentThread().getName() + "正在执行。。。");
testadd();
}
}

public synchronized static void testadd() {
try
{
int c = a + b;
System.out.println(Thread.currentThread().getName() + "正在计算a=" + a
+ " b=" + b + "=====" + c);
System.out.println(Thread.currentThread().getName() + "开始休息");
Thread.sleep(2000);
System.out.println(Thread.currentThread().getName() + "休息完了");
} catch (InterruptedException e)
{
e.printStackTrace();
}

}

}


------解决方案--------------------
能想出这法子的人确实不错, 兄弟这是不可靠的,