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.
Related
I want to start a thread, interrupt it and start a new thread. The Problem is, that this doesn't really work. The first thread starts and gets interrupted, but the following thread gets interrupted before it even can start. So interrupt() interrupts the old and the new thread. The output looks like this:
run()-method starts
Thread Counter:0
Thread Counter:1
Thread Counter:2
Thread Counter:3
Thread Counter:4
Thread Counter:5
Thread Counter:6
8 seconds are over
Thread is not null
Thread will be interrupted now
catch
run()-method starts
catch
8 seconds are over
Thread is not null
Thread will be interrupted now
....
You can see that the thread starts the first time. Then the thread gets interrupted and 'catch' is called. So far, so good. After this, the next thread is going to start, but this time the thread gets interrupted immediately and 'catch' is called right after 'run()-method starts'.
So, I can't figure out why this is happening. I don't want two threads being interrupted in quick succession.
Here is my code:
public class MyRunnable {
static Thread myThread;
static boolean stop;
static Runnable myRunny = new Runnable() {
#Override
public void run() {
System.out.println("run()-method starts");
try {
int j = 0;
while (!stop) {
Thread.sleep(1000);
System.out.println("Thread Counter:"+j);
j++;
}
} catch (InterruptedException e) {
System.out.println("catch");
myThread.interrupt();
}
};
};
public static void main(String[] args){
myThread = null;
while(true) {
stop = false;
if(myThread != null) {
System.out.println("Thread is not null ");
System.out.println("Thread will be interrupted now");
myThread.interrupt();
}
myThread = new Thread(myRunny);
myThread.start();
try {
Thread.sleep(8000);
System.out.print("8 seconds are over "+ "\n");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
catch (InterruptedException e) {
System.out.println("catch");
myThread.interrupt();
}
myThread field is replaced with new reference before calling myThread.interrupt(), so you interrupt the new thread!
So interrupt() interrupts the old and the new thread.
Your diagnosis is incorrect. A call to Thread.interrupt will interrupt one thread once.
What your example is doing is interrupting one thread, and that thread is catching InterruptedException and interrupting a second thread in the exception handler. Two calls to interrupt are being made in quick succession on different threads.
I don't want two threads being interrupted in quick succession.
Well change
} catch (InterruptedException e) {
System.out.println("catch");
myThread.interrupt();
}
to
} catch (InterruptedException e) {
System.out.println("catch");
}
I have 2 threads, the "main" thread which starts a secondary thread to run a little process.
The "main" thread must wait for the secondary thread for a few of seconds to complete the process, after that time, the "main" thread must start again no matter what happened with the process of the secondary thread.
If the secondary process ended earlier, the "main" thread must start to work again.
How can I start a thread from another, wait for the end of execution, and restart the thread after?
I have a code here, but the ExampleRun class, must wait, for example, 10 sec and start again, no matter what happend with MyProcess
public class ExampleRun {
public static void main(String[] args) {
MyProcess t = new MyProcess();
t.start();
synchronized (t) {
try {
t.wait();
} catch (InterruptedException e) {
System.out.println("Error");
}
}
}
}
public class MyProcess extends Thread {
public void run() {
System.out.println("start");
synchronized (this) {
for (int i = 0; i < 5; i++) {
try {
System.out.println("I sleep");
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
flag = true;
System.out.println("Wake up");
notify();
}
}
}
The simplest way to achieve what you want is to use Thread.join(timeout).
Also, do not use synchronized, wait, or notify on Thread objects. This will interfere with the Thread.join implementation. See the documentation for details.
Here's what your main program would look like:
public static void main(String[] args) {
MyProcess t = new MyProcess();
t.start();
try {
t.join(10000L);
} catch (InterruptedException ie) {
System.out.println("interrupted");
}
System.out.println("Main thread resumes");
}
Note that when the main thread resumes after the join() call, it can't tell whether the child thread completed or whether the call timed out. To test this, call t.isAlive().
Your child thread of course could do anything, but it's important for it not to use synchronized, wait, or notify on itself. For example, here's a rewrite that avoids using these calls:
class MyProcess extends Thread {
public void run() {
System.out.println("MyProcess starts");
for (int i = 0; i < 5; i++) {
try {
System.out.println("MyProcess sleeps");
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("MyProcess finishes");
}
}
You can do this with a simple lock method:
public static void main (String[] args)
{
// create new lock object
Object lock = new Object();
// create and start thread
Thread t = new Thread(() ->
{
// try to sleep 1 sec
try { Thread.sleep(1000); }
catch (InterruptedException e) { /* do something */ }
// notify main thread
synchronized (lock) { lock.notifyAll(); }
};
t.start();
// wait for second thread to finish
synchronized (lock)
{
while (t.isAlive())
lock.wait();
}
// second thread finished
System.out.println("second thread finished :)");
}
You could call Thread.join() on the Thread you want to wait for, per the Javadoc,
Waits for this thread to die.
Alternatively, you could use a Future and simply call get(), from its' Javadoc,
Waits if necessary for the computation to complete, and then retrieves its result.
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.
Not sure sure if I am doing this right. I need to make a new thread to write out message certain number of times. I think this works so far but not sure if its the best way of doing it. Then i need to display another message after thread has finished running. How do I do that ? Using isAlive() ? How do i implement that ?
public class MyThread extends Thread {
public void run() {
int i = 0;
while (i < 10) {
System.out.println("hi");
i++;
}
}
public static void main(String[] args) {
String n = Thread.currentThread().getName();
System.out.println(n);
Thread t = new MyThread();
t.start();
}
}
Till now you are on track. Now, to display another message, when this thread has finished, you can invoke Thread#join on this thread from your main thread. You would also need to handle InterruptedException, when you use t.join method.
Then your main thread will continue, when your thread t has finished. So, continue your main thread like this: -
t.start();
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Your Message");
When your call t.join in a particular thread (here, main thread), then that thread will continue its further execution, only when the thread t has completed its execution.
Extending the Thread class itself is generally not a good practice.
You should create an implementation of the Runnable interface as follows:
public class MyRunnable implements Runnable {
public void run() {
//your code here
}
}
And pass an intance of it to the thread as follows:
MyRunnable r = new MyRunnable();
Thread t = new Thread(r);
t.start();
Please check this answer here on SO: Implementing Runnable vs. extending Thread
This is how you can do that.........
class A implements Runnable
{
public void run()
{
for(int i=1;i<=10;i++)
System.out.println(Thread.currentThread().getName()+"\t"+i+" hi");
}
}
class join1
{
public static void main(String args[])throws Exception
{
A a=new A();
Thread t1=new Thread(a,"abhi");
t1.start();
t1.join();
System.out.println("hello this is me");//the message u want to display
}
}
see join() details on
join
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();