Java function runtime limitation

I am trying to build two threads, thread A is the main thread, and thread B is the second thread, thread B updates the variable through a time function (this variable must be shared between both threads, since ultimately thread A must also use this variable), but I I want thread A to terminate thread B if thread B takes too long to complete (using an exception).

I tried the following:

Thread thread = new Thread() {
     public void run() {
         /// run something that could take a long time
     }
};

synchronized (thread) {
    thread.start();
}

System.err.println("Waiting for thread and terminating it if it did not stop.");
try {
   thread.wait(10000);
} catch (InterruptedException e) {
   System.err.println("interrupted.");
}

Should this give the expected behavior of termination of behavior if it has passed more than 10 seconds? The thread object is deleted after waiting because it returns a method that starts the thread.

Right now, what happens with this code, I always get java.lang.IllegalMonitorStateException in the wait (10000) command.

+3
2

IllegalMonitorStateException, wait() , synchronized.

try {
    // you need this to do the wait
    synchronized (thread) {
       thread.wait(10000);
    }
} catch (InterruptedException e) {
    System.err.println("interrupted.");
}

thread, , , :

try {
    thread.join(10000);
} catch (InterruptedException e) {
    Thread.currentThread().interrupt();
    System.err.println("interrupted.");
}

, , , join , (). , thread.isAlive() .

, thread, , 10000 millis, - thread.interrupt(). sleep() wait(), InterruptedException, .

, - :

   while (!Thread.currentThread.isInterrupted()) {
       // do it thread stuff
   }

, , - , , InterruptedException , :

} catch (InterruptedException e) {
    // set the interrupt flag again because InterruptedException clears it
    Thread.currentThread.interrupt();
    System.err.println("interrupted.");
}
+3

. wait Object , , . synchronized, .

: , . Thread.interrupt, , , . , , interrupted() isInterrupted().

+1

All Articles