在线程中使用变量

时间:2012-04-04 21:41:58

标签: java android multithreading

    new Thread(new Runnable() {
        public void run() {
            String response = null;
            //String res = null;
            try {
                response = CustomHttpClient.executeHttpPost("http://abc.org/fypcps/furqan.php");
            } catch (Exception e) {
                // TODO Auto-generated catch block
                //Toast.makeText(context, e.toString(), 0).show();
                //Log.i("furqan", "ya ALLAH madad");
            }  //Enetr Your remote PHP,ASP, Servlet file link  
            String res = response.toString();  
            // res = res.trim();  
            //res= res.replaceAll("\\s+","");  
            //error.setText(res);  
            //if(res.equals("1"))  
                //Log.i("furqan1", res);
            //else  
                //Log.i("furqan2", "no string is captured");
            response1 = res;
        }
      }).start();

这里我的代码response1是一个变量,我已经在线程上面声明了,我想把一个字符串“res”分配给“response1”,但是它给了我封闭的类型error.can任何正文帮助我解决这个问题

3 个答案:

答案 0 :(得分:4)

另一种方法是将Thread之外的String变量声明为 final Array ,这样就可以在线程中分配所需的值。

  final String [] answer = new String[1];      
  answer[0]="init value";
  System.out.println(answer[0]); // return "init value"
  new Thread(new Runnable() {
      public void run() {

          answer[0]="value assigned from the thread";
      }
    }).start();

  try {
    Thread.currentThread().sleep(1000);
  } catch (InterruptedException e) {
    e.printStackTrace();
  }
  System.out.println(answer[0]); //return "value assigned from the thread"

答案 1 :(得分:0)

您无法从匿名类内部向变量分配内容,因为如果在此方案中使用java,则需要变量为final(以防止不必要的副作用)。

您可以尝试通过为变量创建包装来解决此问题:

class StringWrapper {
    public String innerString;
}

final StringWrapper wrapper = new StringWrapper();

new Thread(new Runnable() {
    public void run() {
         ...
         wrapper.innerString = res;
    }
});

答案 2 :(得分:0)

我认为你可以从一个线程中发送一个实例变量的值。 像

这样的东西
package pro.Project;

import android.app.Activity;
import android.os.Bundle;

public class ProjectActivity extends Activity {
    /** Called when the activity is first created. */
    private String foo = "";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        String bar = ""; // Non-final local variable

        Thread t = new Thread(new Runnable() {

            @Override
            public void run() {
                foo ="bar"; // This would work
                bar ="baz"; // This WOULDN'T. As 'bar' is a non-final local variable
            }
        });
        t.start();
    }
}