[英]How to get a value from running instance
Hi Could some one Kindly help here.嗨,有人可以在这里提供帮助。 1)Where i am maintaining one flag for running application if true always my application will run continuously.
1)如果我一直为运行应用程序维护一个标志,我的应用程序将连续运行。
Note:- Parameters are considering as run time arguments.注意:- 参数被视为运行时 arguments。
How second process will change first process value.第二个过程将如何改变第一个过程值。
Exe:-可执行程序:-
class Sample{
public void run(boolean runstate)
{
while(runstate){
//do something
}
}
}
You need to execute "run()" in a separate thread from the main process.您需要在与主进程不同的线程中执行“run()”。 Use this code to break the loop:
使用此代码打破循环:
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);
}
}
Naturally, there have to be 2 threads - one threads runs the above code, the other listens for a request to set the flag.自然地,必须有 2 个线程 - 一个线程运行上述代码,另一个线程侦听设置标志的请求。 Also, the flag has to be accessible to both objects running in the 2 threads.
此外,两个线程中运行的两个对象都必须可以访问该标志。
Here is an example code that starts 2 threads.这是一个启动 2 个线程的示例代码。 One keeps working till
FLAG
has true
.一个人一直工作,直到
FLAG
有true
。 The other thread sleeps for 200ms and then sets FLAG
to false
.另一个线程休眠 200 毫秒,然后将
FLAG
设置为false
。 The other threads detects this and stops.其他线程检测到这一点并停止。
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.