方法及其变量

时间:2013-10-14 00:30:31

标签: java android

我想在另一个类中使用int a的值。我有一个方法来访问另一个类中的a变量。我想使用该方法获取a的值并在我的主类中使用它。

public class Neram {

    private static int a;

    private static void timedel() {
    // TODO Auto-generated method stub
       for(int i=0;i<20000;i++)
       {
          try {
             Thread.sleep(1000);
          } catch (InterruptedException e){}
          a=a+1;
       }
    }
}

我想将int a用作我的其他课程的时间计数器,然后在a变为100时执行代码。

我想要的只是使用一个方法并获取`a的值,然后使用它:

if (a > 100) {
    // say time over
   if(a>150)
     // your taking too long
   if(a>200)
  // that s it Stop RIGHT now
}

5 个答案:

答案 0 :(得分:1)

请使用 TimerTask 处理程序进行这类工作。对您来说更容易。

对于TimerTask: - http://enos.itcollege.ee/~jpoial/docs/tutorial/essential/threads/timer.html

Fro Handler: - http://examples.javacodegeeks.com/android/core/os/handler/android-handler-example/

如果您不想尝试任何其他示例,上面只是示例。


处理程序句柄= new Handler();

Runnable runnable = new Runnable(){

    @Override
    public void run() {
        //what ever you want to do...
    }
};

//如何调用任何方法,如(onCreate)

handle .postDelayed(runnable,100);

*** *计时器任务 公共类JavaReminder {     定时器计时器;

public JavaReminder(int seconds) {
    timer = new Timer();  //At this line a new Thread will be created
    timer.schedule(new RemindTask(), seconds*1000); //delay in milliseconds
}

class RemindTask extends TimerTask {

    @Override
    public void run() {
        System.out.println("ReminderTask is completed by Java timer");
        timer.cancel(); //Not necessary because we call System.exit
        //System.exit(0); //Stops the AWT thread (and everything else)
    }
}

public static void main(String args[]) {
    System.out.println("Java timer is about to start");
    JavaReminder reminderBeep = new JavaReminder(5);
    System.out.println("Remindertask is scheduled with Java timer.");
}

}

输出 Java计时器即将开始 使用Java计时器安排Remindertask。 ReminderTask由Java计时器完成//这将在5秒后打印

答案 1 :(得分:0)

使“int a”成为您尝试从中访问它的任何类的静态成员。只需使用static关键字来声明它。但是,理解为什么它在Java中工作很重要。因此,我强烈建议您快速阅读类成员和Java中的不同访问修饰符。

http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html

另外,如果要从另一个线程内部访问int a,请务必注意同步问题。

答案 2 :(得分:0)

public class Neram {

    public static int a;

    private static void timedel() {
    // TODO Auto-generated method stub
       for(int i=0;i<20000;i++)
       {
          try {
             Thread.sleep(1000);
          } catch (InterruptedException e){}
          a=a+1;

             if (a>100)
              new Main1 (a);
       }
    }
}

将此文件导入到包含主类的包中并进行更改..你只想要这个或其他什么吗?

Main1类必须有像

这样的构造函数
Main1(int b)

答案 3 :(得分:0)

通常,您可以注册一个回调方法,并通过此回调方法在不同的线程之间共享变量值。但是为了访问线程之间的共享变量,您必须同步它以进行保护。例如将其声明为volatile,或使用AtomicInteger,或创建锁。

答案 4 :(得分:0)

似乎更简单的解决方案是让Handler发送一条带有一些延迟量的消息,然后处理你的逻辑而不是让线程执行此操作...