I have a main Mina handler thread is processing and in that thread i made another thread and set it to sleep for specified time. Now i want that this inner thread sleep independently without blocking Handler thread.
following is sample code.
public void messageReceived(IoSession session, Object message) throws Exception {
Integer tts = 5000;
Thread sleepThread = new Thread(obj);
sleepThread.sleep(tts);
}
currently it is blocking main Handler thread.
Thread.sleep() is a static method, so calling sleepThread.sleep(tts) is the same as Thread.sleep(tts). Hence your current thread is just sleeping.
You can't cause another thread to sleep by calling a method on its Thread object. At a push, you could set a flag on the object and your thread could check for the presence of that flag and behave accordingly.
try
final int tts = 5000;
Thread sleepThread = new Thread() {
public void run() {
try {
Thread.sleep(tts);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
};
sleepThread.start();
Related
I have two thread, taskThread, a thread with a long-running task, and a timerThread, a recurrent timer every n milliseconds. I am trying to trigger any function call on taskThread from timerThread.
#Override
public Task<List<Schedule>> createTask() {
return new Task<List<Schedule>>() {
#Override
protected List<Schedule> call() throws Exception {
Task currentTask = this;
Thread taskThread = Thread.currentThread(); //Thread-1,Task thread
Timer checker = new Timer();
checker.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
try {
if(currentTask.isDone()) cancel();
System.out.println("Task thread "+taskThread+" is : "+taskThread.getState());
System.out.println("Timer thread" + Thread.currentThread()+" is : "+Thread.currentThread().getState());
taskThread.wait(); //throws IllegalMonitorStateException
Thread.sleep(300);
Thread.currentThread().notifyAll();
} catch (InterruptedException ex){
System.out.println(ex);
}
}
},0,500);
List<Schedule> result = solveMakespan(this); //Blocking call
checker.cancel(); //cancel timer
return result;
}
};
}
The scenario I am trying to achieve, is making the taskThread wait for the timerThread before continuing, I read about synchronized blocks but I am not sure how to make the timer block acquire the lock since the solveMakespan is declared outside its thread, and declaring it inside the timer would make it execute multiple times.
EDIT : Concerning the nuance about "accessing the task's thread", I'd like to either be able to call .wait() or join() on the Thread that I want to wait from the Timer thread, or for the Task instance to provide a method that would run on its existing thread, but triggerable from the timer instance. The code snippet should hopefully make the goal I'm trying to achieve clear.
So I am attempting to start a new thread from within a thread.
i.e.
function(update):
under certain conditions:
add a new thread running same service as current
Ideally I would like the new thread to run and my current thread to continue executing.
Instead, a new thread is created but only when it is completed does my host thread continue again.
Ideally I need it to execute concurrently, where adding a new thread has the same effect as adding a thread from my originating class.
How can i do this with executor service?
I'm currently initialising as follows:
ExecutorService executorService = Executors.newFixedThreadPool(100);
Add thread function:
final SimulatedAnnealingCallable simulatedAnnealingCallable =
new SimulatedAnnealingCallable(this, schedule);
final Future<Schedule> future = executorService.submit(simulatedAnnealingCallable);
try {
future.get();
} catch (ExecutionException ex) {
ex.getCause().printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
Shutdown occurs later
The reason is that you are blocking your main thread in the future.get().
what actually happens is that your main thread starts a new future task with the executor and than you block the main thread by telling it to wait for the results of the executing task.
one way to handle this is not waiting for the future to complete and instead add functionality to let you know the task has completed using callable.
for example
public interface CompletedTask {
void completed(boolean succes);
}
// change SimulatedAnnealingCallable to receive CompletedTask in constructor
// and call the instanc's completed method
public LogicClass implements CompletedTask {
private void someFunc() {
final SimulatedAnnealingCallable simulatedAnnealingCallable =
new SimulatedAnnealingCallable(this, schedule);
executorService.submit(simulatedAnnealingCallable);
}
public void completed(boolean succes) {
System.out.println("task is completed with " + success);
}
}
HTH,
Gal
I need to kill a thread that is not created in my code. In other words, the thread object is created by api (Eclipse JFace). Here is my code
ProgressMonitorDialog dialog = new ProgressMonitorDialog(null);
try {
IRunnableWithProgress rp = new IRunnableWithProgress(){
#Override
public void run(IProgressMonitor monitor)
throws InvocationTargetException, InterruptedException {
Thread.sleep(3000);
Thread t = Thread.currentThread();
t.getThreadGroup().list();
t.interrupt();
}
};
dialog.run(true, true, rp);
}
catch (Exception e) {
e.printStackTrace();
}
Thread.currentThread() returns a thread with the name "ModalContext". Line t.getThreadGroup().list() returns the following data:
...
Thread[qtp1821431-38,5,main]
Thread[qtp1821431-39,5,main]
Thread[qtp1821431-40,5,main]
Thread[qtp1821431-42 Acceptor0 SelectChannelConnector#0.0.0.0:18080,5,main]
Thread[DestroyJavaVM,5,main]
Thread[ModalContext,5,main]
Variables "dialog" and "rp" do not have reference to their runnable object. And they don't have any method to close or cancel. So I want to kill that thread "ModalContext" directly. Calling t.interrupt() does not work. Thread MoadlContext continues to run. How can I kill the thread? Thanks
The interrupt method doesn't kill the thread. It sets the "interrupted" status on the Thread, and if it's sleeping or waiting on I/O, then that method that it's calling will throw an InterruptedException.
However, you call interrupt on the current thread after sleep finishes, so this will do nothing but set the "interrupted" status.
You can do one of the following:
Have another Thread call interrupt on that Thread. In run(), let the method complete if an InterruptedException is caught or if interrupted() returns true.
Declare a volatile boolean variable (say, isRunning) that is initialized to true in the created thread. That thread will let the run() method complete if it's false. Have another Thread set it to false at the appropriate time.
t.interrupt() does not actually interrupt the thread immediately it only update interrupt status of thread. If your thread contains method which poll the interrupt status (i.e. sleep )only then the thread will be interrupted otherwise the thread simply complete the execution and interrupt status will be ignored.
Consider following example,
class RunMe implements Runnable {
#Override
public void run() {
System.out.println("Executing :"+Thread.currentThread().getName());
for(int i = 1; i <= 5; i++) {
System.out.println("Inside loop for i = " +i);
}
System.out.println("Execution completed");
}
}
public class Interrupted {
public static void main(String[] args) {
RunMe runMe = new RunMe();
Thread t1 = new Thread(runMe);
t1.start();
t1.interrupt();//interrupt ignored
System.out.println("Interrupt method called to interrupt t1");
}
}
OUTPUT
Interrupt method called to interrupt t1
Executing :Thread-0
Inside loop for i = 1
Inside loop for i = 2
Inside loop for i = 3
Inside loop for i = 4
Inside loop for i = 5
Execution completed
Now just add Thread.sleep(200); in run and you will see the InterruptedException.
I have created class by implementing runnable interface and then created many threads(nearly 10) in some other class of my project.How to stop some of those threads?
The simplest way is to interrupt() it, which will cause Thread.currentThread().isInterrupted() to return true, and may also throw an InterruptedException under certain circumstances where the Thread is waiting, for example Thread.sleep(), otherThread.join(), object.wait() etc.
Inside the run() method you would need catch that exception and/or regularly check the Thread.currentThread().isInterrupted() value and do something (for example, break out).
Note: Although Thread.interrupted() seems the same as isInterrupted(), it has a nasty side effect: Calling interrupted() clears the interrupted flag, whereas calling isInterrupted() does not.
Other non-interrupting methods involve the use of "stop" (volatile) flags that the running Thread monitors.
How to stop a thread created by implementing runnable interface?
There are many ways that you can stop a thread but all of them take specific code to do so. A typical way to stop a thread is to have a volatile boolean shutdown field that the thread checks every so often:
// set this to true to stop the thread
volatile boolean shutdown = false;
...
public void run() {
while (!shutdown) {
// continue processing
}
}
You can also interrupt the thread which causes sleep(), wait(), and some other methods to throw InterruptedException. You also should test for the thread interrupt flag with something like:
public void run() {
while (!Thread.currentThread().isInterrupted()) {
// continue processing
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// good practice
Thread.currentThread().interrupt();
return;
}
}
}
Note that that interrupting a thread with interrupt() will not necessarily cause it to throw an exception immediately. Only if you are in a method that is interruptible will the InterruptedException be thrown.
If you want to add a shutdown() method to your class which implements Runnable, you should define your own class like:
public class MyRunnable implements Runnable {
private volatile boolean shutdown;
public void run() {
while (!shutdown) {
...
}
}
public void shutdown() {
shutdown = true;
}
}
Stopping the thread in midway using Thread.stop() is not a good practice. More appropriate way is to make the thread return programmatically. Let the Runnable object use a shared variable in the run() method. Whenever you want the thread to stop, use that variable as a flag.
EDIT: Sample code
class MyThread implements Runnable{
private volatile Boolean stop = false;
public void run(){
while(!stop){
//some business logic
}
}
public Boolean getStop() {
return stop;
}
public void setStop(Boolean stop) {
this.stop = stop;
}
}
public class TestStop {
public static void main(String[] args){
MyThread myThread = new MyThread();
Thread th = new Thread(myThread);
th.start();
//Some logic goes there to decide whether to
//stop the thread or not.
//This will compell the thread to stop
myThread.setStop(true);
}
}
If you use ThreadPoolExecutor, and you use submit() method, it will give you a Future back. You can call cancel() on the returned Future to stop your Runnable task.
Stopping (Killing) a thread mid-way is not recommended. The API is actually deprecated.
However, you can get more details including workarounds here: How do you kill a Thread in Java?
Thread.currentThread().isInterrupted() is superbly working. but this
code is only pause the timer.
This code is stop and reset the thread timer.
h1 is handler name.
This code is add on inside your button click listener.
w_h =minutes w_m =milli sec i=counter
i=0;
w_h = 0;
w_m = 0;
textView.setText(String.format("%02d", w_h) + ":" + String.format("%02d", w_m));
hl.removeCallbacksAndMessages(null);
Thread.currentThread().isInterrupted();
}
});
}`
Given the following Java code:
public class Test {
static private class MyThread extends Thread {
private boolean mustShutdown = false;
#Override
public synchronized void run() {
// loop and do nothing, just wait until we must shut down
while (!mustShutdown) {
try {
wait();
} catch (InterruptedException e) {
System.out.println("Exception on wait()");
}
}
}
public synchronized void shutdown() throws InterruptedException {
// set flag for termination, notify the thread and wait for it to die
mustShutdown = true;
notify();
join(); // lock still being held here, due to 'synchronized'
}
}
public static void main(String[] args) {
MyThread mt = new MyThread();
mt.start();
try {
Thread.sleep(1000);
mt.shutdown();
} catch (InterruptedException e) {
System.out.println("Exception in main()");
}
}
}
Running this will wait for one second and then properly exit. But that is unexpected to me, I expect a dead-lock to happen here.
My reasoning is as follows: The newly created MyThread will execute run(), which is declared as 'synchronized', so that it may call wait() and safely read 'mustShutdown'; during that wait() call, the lock is released and re-acquired upon returning, as described in the documentation of wait(). After one second, the main thread executes shutdown(), which is again synchronized as to not access mustShutdown at the same time as it's being read by the other thread. It then wakes up the other thread via notify() and the waits for its completion via join().
But in my opinion, there's no way that the other thread can ever return from wait(), since it needs to re-acquire the lock on the thread object before returning. It cannot do so because shutdown() still holds the lock while inside join(). Why does it still work and exit properly?
join() method internally calls wait() which will result in releasing of the lock(of Thread object).
See the code of join() below:
public final synchronized void join(long millis)
throws InterruptedException {
....
if (millis == 0) {
while (isAlive()) {
wait(0); //ends up releasing lock
}
}
....
}
Reason why your code sees this and not seen in general:: The reason why your code see this and not is not observed in general, is because the join() method waits() on Thread object itself and consequently relinquishes lock on the Thread object itself and as your run() method also synchronizes on the same Thread object, you see this otherwise unexpected scenario.
The implementation of Thread.join uses wait, which lets go of its lock, which is why it doesn't prevent the other thread from acquiring the lock.
Here is a step-by-step description of what happens in this example:
Starting the MyThread thread in the main method results in a new thread executing the MyThread run method. The main Thread sleeps for a whole second, giving the new Thread plenty of time to start up and acquire the lock on the MyThread object.
The new thread can then enter the wait method and release its lock. At this point the new thread goes dormant, it won't try to acquire the lock again until it is woken up. The thread does not return from the wait method yet.
At this point the main thread wakes up from sleeping and calls shutdown on the MyThread object. It has no problem acquiring the lock because the new thread released it once it started waiting. The main thread calls notify now. Entering the join method, the main thread checks that the new thread is still alive, then waits, releasing the lock.
The notification happens once the main thread releases the lock. Since the new thread was in the wait set for the lock at the time the main thread called notify, the new thread receives the notification and wakes up. It can acquire the lock, leave the wait method, and finish executing the run method, finally releasing the lock.
The termination of the new thread causes all threads waiting on its lock to receive a notification. This wakes up the main thread, it can acquire the lock and check that the new thread is dead, then it will exit the join method and finish executing.
/**
* Waits at most <code>millis</code> milliseconds for this thread to
* die. A timeout of <code>0</code> means to wait forever.
*
* #param millis the time to wait in milliseconds.
* #exception InterruptedException if any thread has interrupted
* the current thread. The <i>interrupted status</i> of the
* current thread is cleared when this exception is thrown.
*/
public final synchronized void join(long millis)
throws InterruptedException {
long base = System.currentTimeMillis();
long now = 0;
if (millis < 0) {
throw new IllegalArgumentException("timeout value is negative");
}
if (millis == 0) {
while (isAlive()) {
wait(0);
}
} else {
while (isAlive()) {
long delay = millis - now;
if (delay <= 0) {
break;
}
wait(delay);
now = System.currentTimeMillis() - base;
}
}
}
To complement the other answers: I see no mention of join() releasing any locks in the API-documentation, so this behavior is actually implementation-specific.
Learn from this:
don't subclass Thread, instead use a Runnable implementation passed to your thread object.
don't synchronize/wait/notify on objects you don't "own", e.g. where you don't know who else might synchronize/wait/notify on it.