繁体   English   中英

将变量传递给方法(Java)

[英]Passing variable into methods (Java)

我是Java的新手,但我遇到了问题。 我已经从Android教程中复制了一些代码,现在我想将整数变量传递到方法run()中,这样我可以为每个循环递增它,然后在后台线程之外捕获它。 我该怎么做?

int gg= 0;    
Thread background = new Thread(new Runnable() {
                    public void run() {
                        try {

                            while (pBarDialog.getProgress() <= 100) {

                                Thread.sleep(100);
                                gg++; // the increment here
                                progressHandler.sendMessage(progressHandler
                                        .obtainMessage());


                            }
                            if (pBarDialog.getProgress() == 100) {
                                pBarDialog.dismiss();

                            }

                        } catch (java.lang.InterruptedException e) {
                            // if something fails do something smart
                        }
                    }

                });
          //catch gg here

您不能为run()方法指定参数。 您可以将int变量声明为字段,并在内部类中使用它。

public class TestActivity extends Activity
{
   private volatile int no;
   .....

}

编辑:(来自@alf的建议)您可以将volatile 修饰符与字段一起使用,以便所有其他线程可以立即看到更改的值。

有一个自己的类,并使用其构造函数传递计数器,我还没有尝试过,但是我将从这样的事情开始:

class MyThread implements Runnable {

   private volatile int counter;

   public MyThread( int counter ) {
       this.counter = counter;
   }

   public void run() {
   ...
   }

   public getCounter() {
      return counter;
   }
}

MyThread mt = new MyThread( 10 );
Thread t = new Thread( mt );
t.start();

// after some time
t.getCounter();
private volatile int gg;

public void myMethod() {
    Thread background = new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                while (pBarDialog.getProgress() <= 100) {
                    Thread.sleep(100);
                    gg++; // the increment here
                    progressHandler.sendMessage(progressHandler.obtainMessage());
                }
                if (pBarDialog.getProgress() == 100) {
                    pBarDialog.dismiss();
                }
            } catch (java.lang.InterruptedException e) {
                // if something fails do something smart
            }
        }

    });

    System.out.println(gg);
}

如果我是您,那么我将研究AtomicInteger ,即incrementAndGet() AndGet incrementAndGet()方法。

gg为字段确实可以使线程访问 gg ,而volatile可以使更改可见,但是由于您的意图不明确,因此我无法确定您没有其他线程增加相同的值:您没有具有原子性,因此一旦有多个线程在执行gg++ ,就很可能会得到错误的结果。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM