Reputation: 859
i have two java files file1 and file2 as follows in package pak
file1:
package pak;
public class file1 {
public static int x=432;
public static void main(String[] args){
System.out.println("y is "+file2.y);
while(x==432) {
System.out.println("x is "+file1.x);
}
}
}
file 2:
package pak;
public class file2 {
public static int y=46;
public static void main(String[] args){
System.out.println("x is "+file1.x);
++file1.x;
System.out.println("x is "+file1.x);
}
}
i will run first file1 and it will be running and when i run file 2 from another shell it should increment x value and it should come out of loop in file 1 can some one pls help me ??????
Upvotes: 0
Views: 278
Reputation: 533870
i will run killjava that kills the process in iostat.java and just before killing i need to perform one action
You can do this with a shutdown hook.
public static void main(String... args) throws InterruptedException {
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Final stats");
}
}));
System.out.println("PID " + ManagementFactory.getRuntimeMXBean().getName());
while (true) {
System.out.println("stats");
Thread.sleep(2000);
}
}
prints
PID 29490@plus-dev-01
stats
stats
stats
stats
stats
Final stats
The last line occurs after I run kill 29490
in another window.
how will i do it for two different processes
This is a complex answer with too many possible solution to mention. (Shared memory, JMS, RMI, signals, Sockets, IPC etc)
Generally, this is done as a high level concept like "stop process" rather than "increment x" even if the result is the same.
The problem is that as its an advanced topic, you would need to have a good understand of interprocess communication to understand the full answer.
The simple solution is; don't do it, find another way to do what you want.
Upvotes: 0
Reputation: 116306
It won't work in such a simple way. Either you
main
methods from two distinct threads within the same process (i.e. Java app), (and you also need to declare file1.x
volatile
for this to work), orfile1.x
so modifications in one won't be visible for the other.Upvotes: 2
Reputation: 13882
You are invoking two different jvm processes. Both the processes will have it's own copy of file1
and file2
. Change in static variable within one process will not be seen by other process.
Upvotes: 0