下面的代码是用两个线程做一种求和操作。输出数组第n个位置是被操作数组前n个数相加。
现在是一个执行完,另一个开始执行
我想让两个线程并行执行,并且结果不能有错误,应该怎么做
public class Pthread{  

public static void main(String args[]){
System.out.println("测试数组为:{1,2,3,4,5,6,7,8,9,10}");
System.out.println("第一个线程执行前5个数相加,第二个执行后5个相加");
//long time = (long)Math.random() * 1000;
//long start = System.nanoTime();

Thread th1 = new thread1();
Thread th2 = new Thread(new thread2());
//th1.setPriority(Thread.MAX_PRIORITY);
//th2.setPriority(Thread.MIN_PRIORITY);
th1.start();
th2.start();
/*for(int i=0;i<100;i++){
System.out.println("Thread main :"+ i);
}
*/
//long end = System.nanoTime();
//System.out.println("主线程执行:"+(end- start)+"纳秒");

}class Work{
static int arr[] = {1,2,3,4,5,6,7,8,9,10};
static int [] arr2 = new int [arr.length];
public static synchronized void sum(int from,int end){

arr2[0] = arr[0];
for(int i=from;i<=end;i++){
arr2[i] = arr[i] + arr2[i-1];
}
for(int i=from;i<=end;i++){
System.out.println(arr2[i]+ " ");
}
}
public static void print(){
for(int i=0;i<arr2.length;i++){
System.out.println(arr2[i] + "");
}
}
}class thread1 extends Thread{

public void run(){

long start = System.nanoTime();
System.out.println("线程1执行:");
try{ //随机睡眠一段时间
sleep((long)Math.random() * 10000);
}catch(InterruptedException e){
}
Work.sum(1,5); //计算sum

long end = System.nanoTime();
System.out.println(" 第一个线程执行:"+(end-start)+"纳秒");
}
}
class thread2 implements Runnable{
public void run(){

long start = System.nanoTime();
System.out.println("线程2执行:");
try{ //随机睡眠一段时间
Thread.sleep((long)Math.random() * 10000);
}catch(InterruptedException e){
}

Work.sum(6,9);

long end = System.nanoTime();
System.out.println(" 第二个线程执行:"+(end-start)+"纳秒");
}
}

解决方案 »

  1.   

    不干涉有些许办法:
    1.取两个变量,分别存储各自的求和结果,然后于各自线程的末尾叠加于一个求总和的变量
    2.只设一个求总和变量,各自线程的工作结果都存于此,但这个前提是要保证该变量读写(先读后写的过程)是同步的,实现这个同步有不同方式,设一同步方法或可以用AtomicInteger等
      

  2.   

    java.util.concurrent.atomic.AtomicInteger
    线程安全
    可以递增递减