class MyThread extends Thread
{
public void run()
{
try
{
for(int i=0 ; i<10 ; i++)
{
System.out.println("I am Lazy Thread.");
Thread.sleep(2000);
}
}
catch (InterruptedException e)
{
System.out.println("I got interrrupted.");
}
}
}
class Test
{
public static void main(String[] args)
{
MyThread t = new MyThread();
t.start(); //after this line
t.interrupt();
System.out.println("end of main.");
}
}
After t.start(); and t.interrupt(); why it is printing end of main first then the child thread statement .
According to multi threading concept it may be child class thread statement also but it is always executing the main Thread statement first .
What is the concept and working procedure behind this .Because its always executing end of main first than others.
why it is printing end of main first then the child thread statement .
This is because each thread run independently, which is the point.
What is the concept and working procedure behind this .Because its always executing end of main first than others.
In particular, threads take time to start, far longer than the time it takes to finish running the main() method.
You can slow down the main thread so see this happen more the way you expect.
public static void main(String[] args) throws InterruptedException {
MyThread t = new MyThread();
t.start(); //after this line
Thread.sleep(1); // thread might not start in this time or might complete.
t.interrupt();
Thread.sleep(1);
System.out.println("end of main.");
}
In fact, 1 milli-second might be too long as a CPU can execute 3,000,000 instructions in a milli-second.
After t.start(); there is two Thread one is main and another is child thread.
both thread are independent to each other ... : main thread initialization already done before the child thread creation and for CPU (Thread Scheduler :T.S.) its is easy to handle and execute the main thread first than the child thread. If T.S. goes for child thread execution than definitely it will takes more time to complete . There are some algorithm which works inside T.S. which threads it wants to choose first and it is always vary form T.S. to T.S.
As the docs say
public void interrupt()
Interrupts this thread.
Unless the current thread is interrupting itself, which is always permitted, the checkAccess method of this thread is invoked, which may cause a SecurityException to be thrown.
If this thread is blocked in an invocation of the wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException.
If this thread is blocked in an I/O operation upon an interruptible channel then the channel will be closed, the thread's interrupt status will be set, and the thread will receive a ClosedByInterruptException.
If this thread is blocked in a Selector then the thread's interrupt status will be set and it will return immediately from the selection operation, possibly with a non-zero value, just as if the selector's wakeup method were invoked.
If none of the previous conditions hold then this thread's interrupt status will be set.
Interrupting a thread that is not alive need not have any effect.
Throws:
SecurityException - if the current thread cannot modify this thread
Note : With threads you don't get any guarantee in the order of how things will be executed unless you explicitly synchronize them
In simple language, preparing a new thread requires a lot of initialization work. Even the main thread takes its own time to start, but because main thread is already initialized and running it completes its execution even when the threads spawned out of it is in their initialization and execution phase.
Related
I have this code:
public class Nit extends Thread {
public void run() {
try {
synchronized(this) {
this.wait();
}
System.out.println("AAA");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Nit n = new Nit();
n.start();
synchronized(n) {
n.notify();
}
}
}
When I run it from cmd it never exits like it is an infinite loop. I don't understand why. Only thing i can think of is that Nit n is still waiting but I don't get why?
You are observing a race condition. You notify before the wait happens. Therefore the wait sits there and waits forever.
If you would invoke this code often enough, you might see it passing sometimes - when the new thread advanced faster then the main thread. One way to make the example work: try adding a call to Thread.sleep(1000) or so before calling notify(). Alternatively, even a println() call on the main thread (before the notify() might change timing enough).
Beyond that: such subtleties are the main reason why you actually avoid using the "low level" primitives such as as wait/notify. Instead, you use the powerful abstractions (like queues) that standard APIs have to offer.
The notify method tells the scheduler to pick a thread to notify, choosing from only those threads that are currently waiting on the same lock that notify was called on.
In this case the n thread doesn't start waiting until after the notification has already happened, so nothing ever wakes the thread up from waiting. You may have assumed that waiting threads will see notifications made before they started waiting, or that the JVM would have to give the n thread CPU time before the main thread proceeds past the call to start, but those assumptions aren't valid.
Introduce a condition flag as an instance member of Nit:
public class Nit extends Thread {
boolean notified = false;
and change Nit's run method to check it:
synchronized (this) {
while (!notified) {
wait();
}
}
Then add a line to the main method so that the main thread can set the flag:
synchronized (n) {
n.notified = true;
n.notify();
}
This way the notify can still happen before n starts waiting, but in that case n will check the flag, see it's true already, and skip waiting.
See Oracle's guarded blocks tutorial:
Note: Always invoke wait inside a loop that tests for the condition being waited for.
Also the API documentation (see Thread.join) discourages the practice of locking on thread objects.
I am writing a program where i invoke multiple threads from my main function. There is a For loop which starts threads in a loop.
I want to implement a functionality where if some exception occurs in one thread then it should stop all the currently running/submitted threads, or the threads in waiting state. And also no more further threads should be submitted from the loop.
P.S. I am maintaining a Map which keeps record of all threads Map <threadName, Thread>
And i am not using executor service.
How to kill or stop all threads and prevent further threads from being submitted after some exception occurs in any one thread.
You can't forcefully stop a thread in Java.
Yes, there are methods like Thread.stop() and related, but they've been deprecated for years for good reason.
Why is Thread.stop deprecated?
Because it is inherently unsafe. Stopping a thread causes it to unlock all the monitors that it has locked. (The monitors are unlocked as the ThreadDeath exception propagates up the stack.) If any of the objects previously protected by these monitors were in an inconsistent state, other threads may now view these objects in an inconsistent state. Such objects are said to be damaged. When threads operate on damaged objects, arbitrary behavior can result. This behavior may be subtle and difficult to detect, or it may be pronounced. Unlike other unchecked exceptions, ThreadDeath kills threads silently; thus, the user has no warning that his program may be corrupted. The corruption can manifest itself at any time after the actual damage occurs, even hours or days in the future.
Because of the above, you shouldn't use those methods, nor rely on them working (many APIs with thread-heavy methods will happily ignore any calls to stop() and interrupt()).
Once we got that out of the way, you can still implement logic for your threads to terminate ASAP when you ask them to, in an elegant manner.
You need to do two things:
1.- Check for Thread.interrupted() inside your run() method. Something like this:
#Override
public synchronized void run() {
while (yourFinishCondition && !Thread.interrupted()) {
// do stuff until you finish, or until the thread is interrupted from the outside
}
}
2.- Invoke interrupt() on every thread from your main method to signal them for termination when you need to, like this:
Thread.UncaughtExceptionHandler h = (thread, exception) -> {
thread0.interrupt();
thread1.interrupt();
thread2.interrupt();
};
A little PoC:
public class Main {
static class MyThread extends Thread {
public MyThread(String s) {
super(s);
}
#Override
public synchronized void run() {
while(!Thread.interrupted()) {
if (new Random().nextInt(1000000) == 7) {
throw new RuntimeException(Thread.currentThread().getName()+" oops!");
}
}
System.out.println(Thread.currentThread().getName()+" interrupted");
}
}
public static void main(String[] args) {
final MyThread thread0 = new MyThread("thread0");
final MyThread thread1 = new MyThread("thread1");
final MyThread thread2 = new MyThread("thread2");
Thread.UncaughtExceptionHandler h = (thread, exception) -> {
System.out.println(exception.getMessage());
thread0.interrupt();
thread1.interrupt();
thread2.interrupt();
};
thread0.setUncaughtExceptionHandler(h);
thread1.setUncaughtExceptionHandler(h);
thread2.setUncaughtExceptionHandler(h);
thread0.start();
thread1.start();
thread2.start();
}
}
Output:
thread2 oops!
thread1 interrupted
thread0 interrupted
Further reading: https://www.securecoding.cert.org/confluence/display/java/THI05-J.+Do+not+use+Thread.stop()+to+terminate+threads
Note that there is no "built in" functionality to stop a thread in java - some methods do exist but all are deprecated since they might cause trouble if the running code is not cooperative. So your code must implement some method to exit the run()-method based on some flag and this must be set from outside the thread. If your threads are using wait() a lot a call to interrupt() might come in handy.
You could write the code to kill all the running threads in finally block or catch block(which might not be recommended)
On killing all the running threads,refer this thread
If I got you question correct, You need to catch the exception and need to keep/maintain the list as a shared object, then call thread.stop() on the other threads will solve the problem right? But the stop method is deprecated in recent versions of java, So you can use thread.yield() to make the thread release the CPU and other resources, But still it will not guarantee the immediate termination of threads.
While I know the theoretical differences between Re-EntrantLocks and synchronized, I'm confused to the below point.
See this statement from an article on Javarevisited comparing synchronized and Lock objects:
One more worth noting difference between ReentrantLock and
synchronized keyword in Java is, ability to interrupt Thread while
waiting for Lock. In case of synchronized keyword, a thread can be
blocked waiting for lock, for an indefinite period of time and there
was no way to control that. ReentrantLock provides a method called
lockInterruptibly(), which can be used to interrupt thread when it is
waiting for lock. Similarly tryLock() with timeout can be used to
timeout if lock is not available in certain time period.
As per the above statement, I did try interrupting the Thread waiting() on synchronized method (i.e blocking wait) and it did throw an InterruptedException. But this behavior is contradictory with what is stated in the above statement.
// this method is called from inside run() method of every thread.
public synchronized int getCount() {
count++;
try {
Thread.sleep(3000);
System.out.println(Thread.currentThread().getName() + " gets " + count);
} catch (InterruptedException e) {
e.printStackTrace();
}
return count;
}
....
....
t1.start();
t2.start();
t3.start();
t4.start();
t2.interrupt();
Here is the output that I got :
Thread 1 gets 1
Thread 4 gets 2
Thread 3 gets 3
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at locks.SynchronizedLockInterrupt.getCount(SynchronizedLockInterrupt.java:10)
at locks.SynchronizedLockInterrupt$2.run(SynchronizedLockInterrupt.java:35)
at java.lang.Thread.run(Unknown Source)
I'm confused if my example is not correct or the quoted statement about synchronized() is incorrect?
Without the rest of the code this question might not be fully answered.
What, I think, you're being confused with here is that you're seeing that, whilst the code would imply you cannot "interrupt" a thread that's blocked on a synchronized lock you are seeing that your count variable seems to be unaffected by the thread which is supposed to have entered into this method.
Important to note that you can technically "interrupt" a blocked thread, as in you can call interrupt() on it and this will set the interrupted flag. Just because a Thread has the interrupted flag set does not mean that it cannot execute any more code. Simply, when it get's to the next code that checks for an interrupted state, that code will likely throw an InterruptedException whilst clearing the flag at the same time. If the person catching the exception intends to do more work, it's their (almost moral) duty to re-set the flag or throw the same.
So, yes, in your example, you are catching the exception that has been thrown by .sleep() on entry, likely before the thread was sleep-ed, you then print the stack trace that proves that.
The outstanding question that might be causing confusion for you; why, then, did my count not increment if this code was allowed to run until the .sleep() method call?
The answer is that the count variable was incremented, you just didn't see the result.
synchronized in Java does not guarantee order and can lead to starvation so t2 just happened to be executed last and you never checked the count before you slept to see that it was already 3
So to answer your question, the documentation is correct and the behaviour is correct.
Interrupting a thread which is waiting "uninterruptedly" on a Lock , ReentrantLock or synchronized block will merely result in the thread waking up and seeing if it's allowed to take the lock yet, by whatever mechanism is in place in the defining lock, and if it cannot it parks again until it is interrupted again or told it can take the lock. When the thread can proceed it simply proceeds with its interrupted flag set.
Contrast to lockInterruptibly where, actually, if you are interrupted, you do not ever get the lock, and instead you "abort" trying to get the lock and the lock request is cancelled.
lock and lockInterruptibly can be mixed use on the same ReentrantLock as the lock will manage the queue and skip requests that were CANCELLED by a finally statement because they were interrupted when waiting on a lock.
In summary:
You can almost always interrupt a thread.
The interrupt flag is usually only cleared on a thread by code that documents that it clears the flag when throwing the InterruptedException , but not all code documents this (lockInterruptibly on ReentrantLock does, but not the same on AbstractQueuedSynchronizer which powers the lock).
Interrupting a thread has different behaviour depending on what it is doing at the time;
A parked thread will be un-parked and have it's flag set, usually then cleared
A thread waiting on a lock / synchronized block will eventually get into the code but with interrupted flag set
A thread waiting on a lockInterruptibly or a get on a future etc will be unparked and behave as documented, aborting the lock acquisition.
synchronized is an intrinsic lock which is beyond the control of JDK.
Synchronization is built around an internal entity known as the intrinsic lock or monitor lock. (The API specification often refers to this entity simply as a "monitor.") Intrinsic locks play a role in both aspects of synchronization: enforcing exclusive access to an object's state and establishing happens-before relationships that are essential to visibility.
When a thread invokes a synchronized method, it automatically acquires the intrinsic lock for that method's object and releases it when the method returns. The lock release occurs even if the return was caused by an uncaught exception.
In your example, you are actually interrupting the sleep as JDK doc mentions.
If this thread is blocked in an invocation of the wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException.
More details about how interrupt() works.
Many methods that throw InterruptedException, such as sleep, are designed to cancel their current operation and return immediately when an interrupt is received.
If have added a simple example to make it clear.
In your example you have already aquired the lock, see your stacktrace.
The code is self explaining.
The problem with synchronized is that it is no interruption point, whereas lock.lockInterruptibly() is. Note that lock.lock() is also not an interruption point.
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Foo {
public static void main(String[] args) throws InterruptedException {
// for the example with synchronized
Object monitor = new Object();
// for the example with locks
Lock lock = new ReentrantLock();
// iam lazy, just use both lock and motitor for this example
Thread one = new Thread(() -> {
lock.lock();
try {
synchronized (monitor) {
System.out.println("Thread one entered monitor");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println("Thread one interrupted");
Thread.currentThread().interrupt();
}
}
} finally {
lock.unlock();
}
});
// uncomment to use the monitor object
// Thread two = new Thread(() -> {
// synchronized (monitor) {
// System.out.println("Thread two entered monitor");
// }
// });
Thread two = new Thread(() -> {
try {
lock.lockInterruptibly();
try {
System.out.println("Thread one entered lock");
} finally {
lock.unlock();
}
} catch (InterruptedException e) {
System.out.println("Thread two interrupted while waiting for lock");
Thread.currentThread().interrupt();
}
});
// start thread one
one.start();
// wait for the thread to start, too lazy to implement notifications
Thread.sleep(1000);
// start thread two
two.start();
// interrupting will wait until thread one finished
two.interrupt();
}
}
If you remove "Thread.sleep(3000)", your 'getCount()' method will not throw exception.
You can only interrupt a thread either in sleep or wait in case of Synchronised method
You're not interrupting the synchronization, you're interrupting the sleep().
This question already has answers here:
How to stop a java thread gracefully?
(6 answers)
Closed 8 years ago.
As i have Written a Simple Java Program to call Thread . below is my code
public class ThreadPoolForParallelExec {
public static void main(String args[]) {
ExecutorService service = Executors.newFixedThreadPool(5);
for (int i = 0; i < 5; i++) {
service.submit(new Task(i));
}
service.shutdown();
}
}
final class Task implements Runnable {
private int taskId;
public Task(int id) {
this.taskId = id;
}
#Override
public void run() {
myclient.intializeAndConnectRemoteMachine(taskId);
Thread.currentThread().stop();
Thread.currentThread().isInterrupted();
}
}
However , I need to terminate the Executor or Thread . I tried Thread.currentThread().stop(); and
Thread.currentThread().stop(); both didnt work :( could you please suggets .
Generally speaking, to kill thread is a bad idea, and in fact, the latest Java specification deprecate that.
Instead, try to finish the thread gracefully within the thread itself. That is the consistent structure.
Just let the method end normally.
Then the Thread will be idle and the ExecutorService will shutdown afterwards.
I think you should call to interrupt() and then wait Threads to finish. Then you could do any actions without having threads running.
you can either use Thread.interrupt() or use volatile flag in run method and set it false when you want to stop thread.
#Override
public void run() {
while (running) {
try {
....
} catch (InterruptedException e) {
running = false;
}
}
}
while running is flag initialized as true.
for more details you can refer this link
The documentation for version 1.5 says:
interrupt
public void interrupt()
Interrupts this thread.
Unless the current thread is interrupting itself, which
is always permitted, the checkAccess method of this thread
is invoked, which may cause a SecurityException to be thrown.
If this thread is blocked in an invocation of the
wait(), wait(long), or wait(long, int) methods of the
Object class, or of the join(), join(long), join(long,
int), sleep(long), or sleep(long, int), methods of this
class, then its interrupt status will be cleared and it
will receive an InterruptedException.
If this thread is blocked in an I/O operation upon an
interruptible channel then the channel will be closed,
the thread's interrupt status will be set, and the
thread will receive a ClosedByInterruptException.
If this thread is blocked in a Selector then the
thread's interrupt status will be set and it will
return immediately from the selection operation,
possibly with a non-zero value, just as if the
selector's wakeup method were invoked.
If none of the previous conditions hold then this
thread's interrupt status will be set.
Throws:
SecurityException - if the current thread cannot modify this thread
Never use Thread.stop. It has been deprecated:
From JLS:
This method is inherently unsafe. Stopping a thread with Thread.stop causes it to unlock all of the monitors that it has locked (as a natural consequence of the unchecked ThreadDeath exception propagating up the stack). If any of the objects previously protected by these monitors were in an inconsistent state, the damaged objects become visible to other threads, potentially resulting in arbitrary behavior. Many uses of stop should be replaced by code that simply modifies some variable to indicate that the target thread should stop running. The target thread should check this variable regularly, and return from its run method in an orderly fashion if the variable indicates that it is to stop running. If the target thread waits for long periods (on a condition variable, for example), the interrupt method should be used to interrupt the wait
The good way to do it is to have the run() of the Thread guarded by a boolean variable and set it to true from the outside when you want to stop it.
Make sure you had made the guarding boolean field volatile to make sure the reading thread sees changes from the writing thread.
My understanding is that threads in theory are executed in parallel. JVM decides; when a resource is available which thread to pick from the waiting thread queue (based on some algorithm).
Hence we can not provide/enforce a sequence of execution for threads.
Say my java application has 3 threads, t1, t2 and t3.
For some specific reason; I want the threads to execute in this order:
t3 then t1 and then t2.
Is it possible to do this? Does java provided any way of doing this?
Use an Executor:
executor.execute(runnable1);
wait();
executor.execute(runnable2);
wait();
executor.execute(runnable3);
wait();
And of course, each Runnable has to end with a notify() statement.
You cannot tell the thread scheduler which order to execute threads in. If you need to ensure that a certain piece of code which is running on thread A must run before another piece of code running on thread B, you must enforce that order using locks or wait()/notify().
For example, you could use a variable which was accessible to both threads as a "flag" to indicate whether it is safe for thread B to go ahead. Thread B could wait() in a loop, checking the value of that variable. Then when it was safe for thread B to run, thread A could set the variable and wake thread B up using notify().
So yes, it is possible to enforce a desired order between things which happen on different threads. Generally, though, you want to avoid writing such low-level, detailed code. It is just too easy to get things wrong and cause subtle, hard-to-find bugs. When you are dealing with multithreaded code, always try to use high-level building blocks if you can.
Don't use threads, is the straightforward answer.
If you don't want code to run out of order, then why are you using threads at all? Just execute things step by step like normal.
If you want certain parts of the threads to run in order, then use standard concurrency mechanisms like locks, wait/notify, and semaphores, but if you just want whole operations to run in a specific order, then...run them in order. Without threads.
Since java 8 this has become very easy using CompletableFuture :
CompletableFuture.runAsync(runnable3)
.thenRunAsync(runnable1)
.thenRunAsync(runnable2);
You can join a thread on another so he'll run when the other one finishes.
You can set order for your threads.
I've tried to modelling your situation:
public class ThreadJoinExample {
private static final Thread FIRST = new Thread( new RunnableImpl(), "first" );
private static final Thread SECOND = new Thread( new RunnableImpl(), "second" );
public static void main(String[] args) {
//here have started current thread or "main" thread that will control above threads
FIRST.start();
//waiting 2 seconds, "stop" your current thread and after current thread will start this "t3" thread until it will dead
try {
FIRST.join(2000);
} catch (InterruptedException e) {
System.out.println();
e.printStackTrace();
}
SECOND.start();
//"stop" your current thread immediately and run "t1" thread until it will dead.
try {
SECOND.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
//Or we can wait for all threads and in the end - finish current main thread
try {
FIRST.join();
SECOND.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Current thread is going die");
}
}
class RunnableImpl implements Runnable{
#Override
public void run() {
System.out.println("Started thread: "+Thread.currentThread().getName());
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread is going die: "+Thread.currentThread().getName());
}
}
Output:
Started thread: first
Started thread: second
Thread is going die: first
Thread is going die: second
Current thread is going die
summary: With .join() method we can move current thread to Runnable state until the time when "joined thread" will dead