简体   繁体   English

如何从另一个 class 处理 object

[英]How to dispose object from another class

I'm not sure if it's actually possible, but let's assume I have two classes.我不确定这是否真的可能,但让我们假设我有两个课程。 One run endless loop inside Thread , another create instance of that class inside method main .一个在Thread内运行无限循环,另一个在方法main内创建该 class 的实例。 So everything works well, but how can I dispose that instance in main and interrupt from executing Thread with endless loop.所以一切正常,但是我如何在main中处理该实例并中断执行 Thread 并使用无限循环。 Here is an example:这是一个例子:

public class Main {
 public static void main(String[] args){
  new ThreadClass();
{
public class ThreadClass{
 public ThreadClass{
  try{
   Thread t = new Thread(new Runnable(){
    int i = 0;
    public void run(){
     while(true){
      i += 1;
      System.out.println(i);
      }
    }
  });
  t.start();
  }catch(Exception e){
   System.out.println("something ");
  }
 }
}

Thanks in advance:)提前致谢:)

ThreadClass has to expose a way (eg, a method) to tell the loop to terminate. ThreadClass必须公开一种方法(例如,方法)来告诉循环终止。 (Typically that involves setting/clearing a volatile flag that the loop uses in its while .) Then main would use that method at...some appropriate time. (通常这涉及设置/清除循环在其while中使用的volatile标志。)然后main将在......某个适当的时间使用该方法。 It's not clear what time you'd want it to, but you'd keep a reference to the instance you created and when that time came, you'd use the method.目前尚不清楚您想要什么时间,但您会保留对您创建的实例的引用,当那个时间到来时,您将使用该方法。

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

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