How do I interrupt execution of a Java method called using javaMethod() in MATLAB?

5 views (last 30 days)
I have a method in my Java class that prints "Hello World" in an infinite loop. The code is as follows:
class Hello
{
public static void main(String args[])
{
while(true)
System.out.println("Hello World\n");
}
}
I am running the above code as follows from MATLAB command prompt:
javaMethod('main', 'Hello', [])
The code runs fine but I am not able to interrupt the execution of main() by typing CTRL+C. Futher, implementing a KeyListener and calling System.exit(0) kills MATLAB as well.

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 27 Jun 2009
When executing a method using javaMethod, MATLAB calls into the JVM and executes that method on the MATLAB thread. In other words, the Java method runs on the same thread as MATLAB. Hence, in this scenario, if we interrupt the function called in javaMethod(), it will stop the execution of MATLAB as well.
To work around this issue, create a new thread, and run the method on that created thread. This will allow interruption of the new thread without exiting MATLAB.
This is demonstrated using a simple Java class that implements the “Runnable” interface to help us create a thread:
public class Bar implements Runnable
{
public void run()
{
while (true)
{
System.out.print(".");
System.out.flush();
try
{
Thread.sleep(1000);
}
catch (InterruptedException ex)
{
Thread.currentThread().interrupt();
break;
}
}
System.out.println("Shutting down thread");
}
public Thread startTh()
{
Bar r = new Bar();
Thread t = new Thread(r);
t.start();
return t;
}
public void stopTh(Thread t)
{
System.out.println("Interrupting thread\n");
t.interrupt();
}
}//end class
The "run" method is meant to contain the code that we wish to execute on a new thread. To simulate this, we are running an infinite loop and printing a period ('.').
The second method “startTh()” creates a thread and starts it. The third method “stopTh()” stops the running thread.
Follow the steps below to execute the code:
1. Create a file named Bar.java
2. Compile the code by invoking the Java compiler on Bar.java:
javac Bar.java
3. From the MATLAB command prompt, execute the following:
>> x = javaObject('Bar'); % this will give us a handle to the class object.
>> y = x.startTh(); % this will create and start the thread.
>> x.stopTh(y); %this will stop the thread whenever typed on MATLAB command prompt.
As mentioned, running the code will start printing ‘...’ on MATLAB command prompt. This will move the MATLAB console arrows ">>" to the right as it gets printed (……>>). The line calling System.out.print(".") can be substituted with your own custom code.

More Answers (0)

Tags

No tags entered yet.

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!