繁体   English   中英

如何从正在运行的实例中获取值

[英]How to get a value from running instance

嗨,有人可以在这里提供帮助。 1)如果我一直为运行应用程序维护一个标志,我的应用程序将连续运行。

  1. 如果标志为假,则必须停止运行应用程序。

注意:- 参数被视为运行时 arguments。

第二个过程将如何改变第一个过程值。

可执行程序:-

class Sample{


    public void run(boolean runstate)
    {
    
    while(runstate){
    //do something
    }
    
    }
    
    }

您需要在与主进程不同的线程中执行“run()”。 使用此代码打破循环:

class Sample{

    private boolean runstate;

    public void run(boolean runstate) // this runs in a separate thread...
    {
        this.runstate = runstate;
        
        while(runstate)
        {
            //do something
        }
    
    }
    
    public void setRunstate(boolean newrunstate)
    {
        this.runstate = newrunstate;
    }
    
}

class Other{

    void foo(Sample sample) // this runs in a separate thread...
    {
        sample.setRunstate(false);
    }

}

自然地,必须有 2 个线程 - 一个线程运行上述代码,另一个线程侦听设置标志的请求。 此外,两个线程中运行的两个对象都必须可以访问该标志。

这是一个启动 2 个线程的示例代码。 一个人一直工作,直到FLAGtrue 另一个线程休眠 200 毫秒,然后将FLAG设置为false 其他线程检测到这一点并停止。

package practice.soflow.concurrent;

import java.util.concurrent.atomic.AtomicReference;

public class FlagSetting{
    private static AtomicReference<Boolean> FLAG = new AtomicReference<Boolean>( Boolean.TRUE );

    public static void main( String[] args ){
        /* Main activity thread. This depends upon the status of FLAG. */
        new Thread( () -> {
            while( FLAG.get() ){
                //do something
                System.out.println( "Hi" );
            }
        } ).start();

        /* The controller thread. This changes the value of FLAG.
         * In this example, it will set it to false after 2 s; */
        new Thread( () -> {
            try{
                Thread.sleep( 200 );
            }
            catch( InterruptedException e ){}

            FLAG.set( Boolean.FALSE );
        } ).start();

    }
}

暂无
暂无

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

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