gpt4 book ai didi

java - 我的代码中线程 "Thread-2"java.lang.NullPointerException.error 中出现异常

转载 作者:行者123 更新时间:2023-11-30 03:55:24 25 4
gpt4 key购买 nike

我的代码可以工作(至少在某种程度上),并且我必须更改一些内容,因为现在它甚至无法启动。代码中没有显示错误,但是当我尝试运行它时,会出现以下内容:

Exception in thread "Thread-2" java.lang.NullPointerException
at azsystem3.Add.run(Main.java:57)
at java.lang.Thread.run(Thread.java:662)

and (Main.java:57) 是这一行:sum.s+=a[i];我如何解决它?这是我的相关代码:

package azsystem3;

import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class Fill implements Runnable{

int []a;
static Random b = new Random();
int start;
int end;
public Fill(int[]a,int start,int end){
this.a=a;
this.start=start;
this.end=end;
}
public void run(){

for(int i=this.start;i<this.end;i++){
a[i]=b.nextInt(100);

}
}
}
class value{
int s;
}


class Add implements Runnable{
value sum;
Lock L ;
int[]a;
int start;
int end;

//public long sum=0;
public Add(int[]a,int start, int end,Lock L,value s){

this.L=L;
this.start=start;
this.end=end;
sum=s;

}

public void run(){
int i;
for( i=start;i<end;i++)
L.lock();
sum.s+=a[i];
L.unlock();

}
}
class main {


public static void main(String[] args) {

value sum=new value();
Lock Lock=new ReentrantLock();
int[] array = new int[100000];

Scanner sc=new Scanner (System.in);
System.out.println ("Enter number : ");
int n = sc.nextInt();
int tmp = 100000 / n;
Thread[] t = new Thread[n];
for (int i = 0; i < n; i++) {
t[i] = new Thread(new Fill(array, (i) * tmp, (i + 1) * tmp));
t[i].start();
}

for (int i = 0; i < n; i++) {
try {
t[i].join();
} catch (InterruptedException exception) {
}
}
Thread[] t1 = new Thread[n];
Add[] add = new Add[n];
long start = System.currentTimeMillis();
for (int i = 0; i < n; i++) {
add[i] = new Add(array, (i) * tmp, (i + 1) * tmp,Lock,sum);
t1[i] = new Thread(add[i]);
t1[i].start();
}

for (int i = 0; i < n; i++) {
try {
t1[i].join();
} catch (InterruptedException exception) {
}
}
long end = System.currentTimeMillis();

System.out.println("sum : " + sum);
System.out.println("time : " + (end - start) + "ms");



}
}

有什么建议吗?

最佳答案

线程安全不仅需要锁定代码中的 run() 方法,而且还应该使类 Add 的私有(private)成员,尤其是 sum 成员,最终。否则,线程可能会看到 value 类型的未完全初始化的对象,其中 sum 成员仍为 null

并注意:请尝试遵循标准 Java 代码约定,以获得更好的可读性。

另一个观察,这段代码

for( i=start;i<end;i++) // missing opening bracket {
L.lock();
sum.s+=a[i];
L.unlock(); // missing closing bracket }

相当于:

for( i=start;i<end;i++) {
L.lock();
}

sum.s+=a[i];
L.unlock();

由于括号处理不当并因此锁定,我对这里的任何线程安全都不信任。

关于java - 我的代码中线程 "Thread-2"java.lang.NullPointerException.error 中出现异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23347516/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com