我认为我有同步问题...它可能太基础了..请帮助..
我有一个线程,其 run 方法如下
public void run()
{
while(true)
{
try {
for (int i = 0; i < 100; i++) {
buf.append(hello + (myint++));
}
buf.append("\n");
adapter.setData(buf.toString());
buf = null;
buf = new StringBuffer();
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(TestThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
我在每次运行中创建新的字符串数据并将其传递给适配器类 setData 方法..
在适配器类中我的setData是这样的..
public boolean setData(String sb){
str = sb;
if(str != null && !str.equalsIgnoreCase("")){
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
System.out.println("inside run.....");
System.out.println("str length:- "+str.length());
//do sth after this..
}
}
但是偶尔我会在 str.length() 行遇到空指针异常...即使我尝试在第一个运行方法中使用 buf.toString() 创建一个新字符串,我也会得到这个异常。
我做错了什么?
提前致谢..
最佳答案
那是因为 str 是一个类变量。如果您没有理由为某人使用其他引用,请尝试以下操作:
public boolean setData(final String str){
if(str != null && !str.equalsIgnoreCase("")){
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
System.out.println("inside run.....");
System.out.println("str length:- "+str.length());
//do sth after this..
}
}
关于Java多线程同步问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1361899/