Java Code:
// Create a second thread.
class NewThread implements Runnable
{
Thread t;
NewThread()
{
t = new Thread(this, "Demo Thread"); // Create a new, second thread
System.out.println("Child thread: " + t);
t.start(); // Start the thread
}
public void run() // This is the entry point for the second thread.
{
justCall();
}
public synchronized void justCall()
{
try
{
for(int i = 10; i > 0; i--)
{
System.out.println("Child Thread: " + i);
Thread.sleep(10000);
}
}
catch (Exception e)
{
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
class ThreadDemo
{
public static void main(String args[])
{
NewThread nt = new NewThread(); // create a new thread
try
{
for(int i = 5; i > 0; i--)
{
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
here you can delete the synchronized justCall() method and you can initialize a synchronization block in a run() method(put justCall() method's code in a synchronized block).
How to synchronize child code here? Please Help. I read that Thread.sleep() method never releases the lock while it is executing in the synchronization block or method. But in my code main thread and child code executes concurrently. Please help to synchronize the child code using Thread.sleep() method.
When two threads synchronize on the same object, they will not both run that same code. This allows many different threads to cooperate running in many different areas of code at the same time.
A synchronized on a non-static method creates a lock on the this object. If it had been a static method the lock would have been on the Class object for the NewThread class. Any class and any instance of any class can have a syncronized on it and thus create a lock.
You have only one thread running in the synchronized area. So, while it is locked, no other thread is attempting to run the locked code. No other thread is attempting to synchronize on the nt instance of the NewThread class.
You might want to try doing this:
NewThread nt1 = new NewThread(); // create a new thread
NewThread nt2 = new NewThread(); // create a 2nd new thread
Then leave off the looping in the main class.
Related
I am writing a program to test how a thread can keep waiting if another thread has acquired lock on same object but after looking at output I am not sure how locking works in java. Here is what i have written:
public class Locking {
synchronized void methodA() {
System.out.println("inside A , " + Thread.currentThread().getName());
}
public static void main(String[] args) throws InterruptedException {
new Locking().execute();
}
private void execute() throws InterruptedException {
Thread t1 = new Thread(new MyThread());
t1.setName("t1");
Thread t2 = new Thread(new MyThread());
t2.setName("t2");
t1.start();
Thread.sleep(5000);
t2.start();
}
class MyThread implements Runnable {
#Override
public void run() {
while (true) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
methodA();
}
}
}
}
I expected thread t2 to be waiting forever and program will print only
inside A , t1
but when i run the program , I get following output:
inside A , t1
inside A , t2
Can anyone explain what is going on here?
I am writing a program to test how a thread can keep waiting if
another thread has acquired lock on same object
The single lock is here :
synchronized void methodA() {
System.out.println("inside A , " + Thread.currentThread().getName());
}
It takes the locks on the current instance but no statement in your code locks in a way where a thread could wait forever the lock.
Look at my comments :
#Override
public void run() {
while (true) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// the lock is set here
methodA();
// and that is released here
}
}
Make the synchronized method never releases the lock and only one of the thread will be able to enter in :
synchronized void methodA() {
while (true) {
System.out.println("inside A , " + Thread.currentThread()
.getName());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// handle it
}
}
}
prints :
inside A , t1
inside A , t1
inside A , t1
...
Her are some other examples to play with threads.
Replace sleep() by wait() and the current thread will release the lock :
synchronized void methodA() {
while (true) {
System.out.println("inside A , " + Thread.currentThread()
.getName());
try {
wait();
} catch (InterruptedException e) {
// handle it
}
}
}
prints :
inside A , t1
inside A , t2
Use notify() (to notify a waiting thread) and wait() (to make the current thread wait and release the lock if it has) to make threads collaborating between them :
synchronized void methodA() {
while (true) {
notify();
System.out.println("inside A , " + Thread.currentThread()
.getName());
try {
wait();
} catch (InterruptedException e) {
// handle it
}
}
}
prints :
inside A , t1
inside A , t2
inside A , t1
inside A , t2
...
That is intended situation.
Your t1 thread is waiting in another thread not main thread.
In your main thread(make threads and call start()), just waiting 5 seconds and start thread2
your synchronized method is synchronizing only when thread 1 calls that method not forever.
After thread1 calls synchorinized method and return, thread1 is stopping 5seconds.
In that time, thread2 can use that method.
The keyword synchronized infront of a method means, that the method cannot be called by two threads at the same time.
As soon as the method is called by a thread, other threads trying to call that same method are blocked until the first thread returns from that method. Afterwards the other threads calling the same method can automatically continue with the call (one at a time).
You implicit lock with synchronized is working for a short period - that is the println after that the lock is released. Both of your threads are racing to obtain the lock there.
Change your code to this and you will see the behavior you want
class MyThread implements Runnable {
#Override
public void run() {
methodA();
}
}
synchronized void methodA() {
while(true)
System.out.println("inside A , " + Thread.currentThread().getName());
}
as you can see this program implements Thread. my question is that how can i interrupt the thread and show the catch block message?
as i know the main thread should finish after child thread but what i consider here is my main thread finish before child thread second question is how can you explain it?
public class cycleone implements Runnable {
int cases;
Thread thrd;
cycleone(int pooya){
cases=pooya;
}
//child thread
public void run(){
try{
for(int i=0;i<=14;i++){
System.out.println("this is "+i+""+cases);
Thread.sleep(600);
}
}
catch(InterruptedException ext){
System.out.print("no");
}
}
}
public class cycletwo {
public static void main(String[] args) {
cycleone one=new cycleone(4);
Thread newThrd=new Thread(one);
newThrd.start();
// main thread
try{
for(int i=0;i<=20;i++){
System.out.println("/");
Thread.sleep(200);
}
}
catch(InterruptedException exc) {
System.out.println("thread is end");
}
System.out.println("thread is ending");
}
}
1) You can interrupt the Thread by calling: newThrd.interrupt() in your main method right after the try/catch block
2) The main thread finishes before the child thread because 20 times per 200ms Thread.sleep() means it's life time is >=20*200 ms
and the child thread's life time is >=14*600 ms
One way you can send an interrupt to the cycleone class is to call the Thread.interrupt method on the newThrd instance you create in cycletwo.
I was trying to create A Java dead lock program . I know in real time we wont be creating any dead lock in thread. Unfortunately I have been asked in one of the interview to writing a "Deadlock program using two threads". So here it is
package Thread.DeadLock;
public class deadLock2 {
static ThreadSample1 t1 = new ThreadSample1();
static ThreadSample2 t2 = new ThreadSample2();
public static void main(String args[]) {
t1.start();
t2.start();
}
public static class ThreadSample1 extends Thread {
public void run() {
System.out.println("In first run method");
try {
System.out.println("Holding lock in first one");
synchronized (t1) {
System.out.println("t1 going to wait for t2");
t1.wait();
System.out.println("t1 finished for waiting");
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static class ThreadSample2 extends Thread {
public void run() {
System.out.println("In second run method");
try {
System.out.println("Holding lock for second one");
synchronized (t2) {
System.out.println("t2 going to wait for t1");
t2.wait();
System.out.println("t2 finished for waiting");
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
I can see the program is getting stuck. I am assuming that it in deadlock situation. t1.start() waits for t2 to finish its task and t2.start() waits for t1 to finish its task. Now while I try to remove the deadlock by notifying the waiting thread using using t1.notify() I get IllegalMonitorStateException.
Can somebody tell in this situation how to remove the deadlock without causing any situation.
First, this is not deadlock. As you correctly described, deadlock is usually situation when there is circular dependency between two or more threads waiting for resources that is held by other thread.
Here, each thread independently waits for notification on itself which is actually not delivered by anybody else in the system. Even if there is no deadlock.
Secondly, IllegalMonitorStateException means that you try to notify/wait on monitor which is not held by the thread. In other words, there is no synchronized prior to notify/wait.
Third, to achieve real deadlock you can do something like this:
synchronized(t1) {
synchronized(t2) {
t2.wait();
}
t1.notify();
}
and vice versa for the other thread.
You can not call notify()/notifyAll() unless the current thread owns that object's monitor. To do that, you must synchronize on it, as you did with wait()
The Javadocs for wait() mention this:
This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.
Throws:
IllegalMonitorStateException – if the current thread is not the owner of this object's monitor.
And from notify():
A thread becomes the owner of the object's monitor in one of three
ways:
By executing a synchronized instance method of that object.
By executing the body of a synchronized statement that synchronizes on the object.
For objects of type Class, by executing a synchronized static method of that class.
See this answer:
Java Wait and Notify: IllegalMonitorStateException
package pck.pramod.geekforgeeks;
public class ThreadDeadlock {
public static Object Lock1 = new Object();
public static Object Lock2 = new Object();
public static void main(String args[]) {
System.out.println(Lock1.toString() + " " + Lock2.toString());
ThreadDemo1 T1 = new ThreadDemo1(Lock1, Lock2, "T1");
ThreadDemo1 T2 = new ThreadDemo1(Lock2, Lock1, "T2");
T1.start();
T2.start();
}
}
class ThreadDemo1 extends Thread {
Object lock1;
Object lock2;
String name;
public ThreadDemo1(Object lock1, Object lock2, String name) {
this.lock1 = lock1;
this.lock2 = lock2;
this.name = name;
}
public void run() {
synchronized (lock1) {
System.out.println(name + " Holding lock ..." + lock1.toString());
try {
Thread.sleep(10);
} catch (InterruptedException e) {
}
System.out.println(name + " Waiting for lock ..." + lock2.toString());
synchronized (lock2) {
System.out.println(name + " Holding lock ..." + lock1.toString() + " " + lock2.toString());
}
}
}
}
I found this code on a tutorial website:
class NewThread implements Runnable {
Thread t;
NewThread() {
// Create a new, second thread
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
t.start(); // Start the thread
}
// This is the entry point for the second thread.
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
// Let the thread sleep for a while.
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
public class ThreadDemo {
public static void main(String args[]) {
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(100);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
In the following line, what is the purpose of the arguments, and what is the meaning of this in the first argument:
t = new Thread(this, "Demo Thread");
Also, what is the expected behaviour (flow) of this code?
When creating a new Thread object you must pass in a Runnable object (which does the actual work in its run() method) as the first argument to the constructor. The second argument is a name for the thread. So, in your code, the following line in the NewThread class constructor:
t = new Thread(this, "Demo Thread");
Creates a new Thread object t named Demo Thread using itself (an instance of NewThread) as the Runnable task, since it implements the Runnable interface. Then, when t.start() is called, the run() method of the NewThread instance t is called.
The API documentation for java.lang.Thread and java.lang.Runnable give more details.
So, your code creates a NewThread object, which starts a child thread in the constructor running the Child Thread loop, and the Main Thread loop is executed by the rest of the code in your main() method. I would expect to see output from the child thread interleaved with output from the main thread when this is run.
Also, when catching InterruptedException and not re-throwing it, it is good practice to restore the interrupted status of the thread, something like this:
} catch (InterruptedException ie) {
System.out.println("Interrupted: " + ie.getMessage());
Thread.currentThread().interrupt();
}
This tutorial by Brian Goetz is very good if you want to learn more about Java threading. It's part of an IBM developerWorks Java concurrency training module.
The line t = new Thread(this, "Demo Thread") is creating a new thread passing the instance of java.lang.Runnable that the thread should execute and the name to give the thread (commonly used during logging operations).
It's a bit weird to have the class implementing java.lang.Runnable create the thread itself. Take a look at the examples of how to use threads on the JavaDoc for java.lang.Thread.
The constructor used in t = new Thread(this, "Demo thread") allows to pass a target. The target must be a Runnable. The target's run() method will be invoked as a result of starting t, so the Thread is created and runs. See the documentation
That's some seriously messed up code up there. OP, you did not write this, but you'll take heat just for stumbling on it.
First of all: The NewThread is not a thread, it's a Runnable. Not the same thing, and for a reason. But then its constructor declares a new thread and starts it right away, turning the Runnable into some sort of a Zombie Thread, which defeats the whole purpose of having a Runnable in the first place, and is just a terrible idea, because if you wanted a Thread, you'd declare a Thread, not a Runnable. What if you want to use the Runnable in a ThreadPool? What if you want to define more than one of these Runnables and start them in a orderly fashion? What if the Runnable one day becomes a Callable, where would you see its Future?
Then, to add insult to injury, the code has concurrent code in the main thread. This servers no educational purpose, and has almost no real-life value, because in real life, you normally don't mix threaded code like that, you'd rather have one control thread (main) and 1..n worker threads (controlled by main).
The point of Threads and Runnables is to separate the functional description of the task (that's the Runnable) from the life-cycle behavior (that's the Thread). Parallel execution and scalability is a nice side benefit. So let's refactor the tutorial code to reflect that:
class Countdown implements Runnable {
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
public class ThreadDemo2 {
public static void main(String args[]) {
Thread t = new Thread(new Countdown());
t.start();
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(100);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
That's better. Now the Runnable does no longer pretend to be a Thread, nor does it even care about when or how or by whom it is going to be run. All it does is implement run() which does what the task is supposed to do, and the main thread gives this Runnable as a constructor argument to a new Thread and then start()s it, which in turn means the new Thread will call the Runnable's run(). But we can do better: the two threads do essentially the same thing, so we should implement them that way:
class Countdown implements Runnable {
final String name;
final int length;
final int skip;
public Countdown(String name, int length, int skip) {
this.name = name;
this.length = length;
this.skip = skip;
}
public void run() {
try {
for(int i = length; i > 0; i--) {
System.out.println(name + ": " + i);
Thread.sleep(skip);
}
} catch (InterruptedException e) {
System.out.println(name + " interrupted.");
}
System.out.println("Exiting " + name);
}
}
public class ThreadDemo3 {
public static void main(String args[]) {
Thread t1 = new Thread(new Countdown("Child One", 5, 50));
Thread t2 = new Thread(new Countdown("Child Two", 5, 100));
t1.start();
t2.start();
}
}
Now we have separated functionality from life-cycle management. Countdown is it's own class which does exactly what the name says and not more, and there is no more worker logic in main. Main just invokes countdowns and starts them.
OP, my biggest advice is: find a better tutorial. The Brian Goetz tutorial mentioned by grkvlt above is much better. You might want to invest some money on books by Goetz ("Java Concurrency in Practice") and Doug Lea ("Concurrent Programming in Java"), too.
I'm trying to understand how threads work, and I wrote a simple example where I want to create and start a new thread, the thread, display the numbers from 1 to 1000 in the main thread, resume the secondary thread, and display the numbers from 1 to 1000 in the secondary thread. When I leave out the Thread.wait()/Thread.notify() it behaves as expected, both threads display a few numbers at a time. When I add those functions in, for some reason the main thread's numbers are printed second instead of first. What am I doing wrong?
public class Main {
public class ExampleThread extends Thread {
public ExampleThread() {
System.out.println("ExampleThread's name is: " + this.getName());
}
#Override
public void run() {
for(int i = 1; i < 1000; i++) {
System.out.println(Thread.currentThread().getName());
System.out.println(i);
}
}
}
public static void main(String[] args) {
new Main().go();
}
public void go() {
Thread t = new ExampleThread();
t.start();
synchronized(t) {
try {
t.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for(int i = 1; i < 1000; i++) {
System.out.println(Thread.currentThread().getName());
System.out.println(i);
}
synchronized(t) {
t.notify();
}
}
}
You misunderstand how wait/notify works. wait does not block the thread on which it is called; it blocks the current thread until notify is called on the same object (so if you have threads A and B and, while in thread A, called B.wait(), this will stop thread A and not thread B - for as long as B.notify() is not called).
So, in your specific example, if you want main thread to execute first, you need to put wait() inside the secondary thread. Like this:
public class Main {
public class ExampleThread extends Thread {
public ExampleThread() {
System.out.println("ExampleThread's name is: " + this.getName());
}
#Override
public void run() {
synchronized (this) {
try {
wait();
} catch (InterruptedException e) {
}
}
for(int i = 1; i < 1000; i++) {
System.out.println(Thread.currentThread().getName());
System.out.println(i);
}
}
}
public static void main(String[] args) {
new Main().go();
}
public void go() {
Thread t = new ExampleThread();
t.start();
for(int i = 1; i < 1000; i++) {
System.out.println(Thread.currentThread().getName());
System.out.println(i);
}
synchronized(t) {
t.notify();
}
}
}
However, even this code may not work like you want. In a scenario where the main thread gets to the notify() part before the secondary thread had a chance to get to the wait() part (unlikely in your case, but still possible - you can observe it if you put Thread.sleep at the beginning of the secondary thread), the secondary thread will never be waken up. Therefore, the safest method would be something similar to this:
public class Main {
public class ExampleThread extends Thread {
public ExampleThread() {
System.out.println("ExampleThread's name is: " + this.getName());
}
#Override
public void run() {
synchronized (this) {
try {
notify();
wait();
} catch (InterruptedException e) {
}
}
for(int i = 1; i < 1000; i++) {
System.out.println(Thread.currentThread().getName());
System.out.println(i);
}
}
}
public static void main(String[] args) {
new Main().go();
}
public void go() {
Thread t = new ExampleThread();
synchronized (t) {
t.start();
try {
t.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for(int i = 1; i < 1000; i++) {
System.out.println(Thread.currentThread().getName());
System.out.println(i);
}
synchronized(t) {
t.notify();
}
}
}
In this example the output is completely deterministic. Here's what happens:
Main thread creates a new t object.
Main thread gets a lock on the t monitor.
Main thread starts the t thread.
(these can happen in any order)
Secondary thread starts, but since main thread still owns the t monitor, the secondary thread cannot proceed and must wait (because its first statement is synchronized (this), not because it happens to be the t object - all the locks, notifies and waits could as well be done on an object completely unrelated to any of the 2 threads with the same result.
Primary thread continues, gets to the t.wait() part and suspends its execution, releasing the t monitor that it synchronized on.
Secondary thread gains ownership of t monitor.
Secondary thread calls t.notify(), waking the main thread. The main thread cannot continue just yet though, since the secondary thread still holds ownership of the t monitor.
Secondary thread calls t.wait(), suspends its execution and releases the t monitor.
Primary thread can finally continue, since the t monitor is now available.
Primary thread gains ownership of the t monitor but releases it right away.
Primary thread does its number counting thing.
Primary thread again gains ownership of the t monitor.
Primary thread calls t.notify(), waking the secondary thread. The secondary thread cannot continue just yet, because the primary thread still holds the t monitor.
Primary thread releases the t monitor and terminates.
Secondary thread gains ownership of the t monitor, but releases it right away.
Secondary thread does its number counting thing and then terminates.
The entire application terminates.
As you can see, even in such a deceptively simple scenario there is a lot going on.
You are lucky that your program terminates at all.
When you call t.wait() your main threads stops and waits indefinitely on a notification.
It never gets it, but I believe is awaken by spurious wakeup when the secondary thread finishes. (Read here on what a spurious wakeup is).
ExampleThread doesn't wait() or notify(), and isn't synchronized on anything. So it will run whenever it can without any coordination with other threads.
The main thread is waiting for a notification which never comes (this notification should be sent by another thread). My guess is that when the ExampleThread dies, the main thread is woken "spuriously," and completes.
The thread that should wait for another to complete must perform the call to wait() inside a loop that checks for a condition:
class ExampleThread extends Thread {
private boolean ready = false;
synchronized void ready() {
ready = true;
notifyAll();
}
#Override
public void run() {
/* Wait to for readiness to be signaled. */
synchronized (this) {
while (!ready)
try {
wait();
} catch(InterruptedException ex) {
ex.printStackTrace();
return; /* Interruption means abort. */
}
}
/* Now do your work. */
...
Then in your main thread:
ExampleThread t = new ExampleThread();
t.start();
/* Do your work. */
...
/* Then signal the other thread. */
t.ready();