In Java: how can I do a thread view through another thread?

Sorry if the question is pretty simple. I am newbie.

I need to create a thread that calibrates something while the first thread is running, the other should measure if the first thread calculates a function at the specified time. If not, he should throw an exception. Otherwise, it returns a response.

+4
source share
4 answers

I would take java.util.concurrent components - a simple example

public void myMethod() { // select some executor strategy ExecutorService executor = Executors.newFixedThreadPool(1); Future f = executor.submit(new Runnable() { @Override public void run() { heresTheMethodToBeExecuted(); } }); try { f.get(1000, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { // do something clever } catch (ExecutionException e) { // do something clever } catch (TimeoutException e) { // do something clever } } 
+5
source

Ask your thread to report the synchronization object when it is finished, and ask another thread to wait x the number of milliseconds for it to end.

 public class Main { private static final Object mThreadLock = new Object(); static class DoTaskThread extends Thread { public void run() { try { int wait = new Random().nextInt(10000); System.out.println("Waiting " + wait + " ms"); Thread.sleep(wait); } catch (InterruptedException ex) { } synchronized (mThreadLock) { mThreadLock.notifyAll(); } } } /** * @param args the command line arguments */ public static void main(String[] args) { synchronized (mThreadLock) { DoTaskThread thread = new DoTaskThread(); thread.start(); try { // Only wait 2 seconds for the thread to finish mThreadLock.wait(2000); } catch (InterruptedException ex) { } if (thread.isAlive()) { throw new RuntimeException("thread took too long"); } else { System.out.println("Thread finished in time"); } } } } 
+3
source

Take a look at http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/ExecutorService.html#awaitTermination(long,%20java.util.concurrent.TimeUnit ) which allows you to deal with by doing this without resorting to thread synchronization yourself.

+1
source

join much easier than using locks.

join (millis)
millis more millis milliseconds for this thread to die. A wait time of 0 means wait forever.

Code example:

 Thread calcThread = new Thread(new Runnable(){ @Override public void run() { //some calculation } }); calcThread.start(); //wait at most 2secs for the calcThread to finish. calcThread.join(2000); //throw an exception if the calcThread hasn't completed. if(calcThread.isAlive()){ throw new SomeException("calcThread is still running!"); } 
+1
source

Source: https://habr.com/ru/post/1334242/


All Articles