Java code Multiple Thread, Wait to start other - java

I a trying to find out, after complete first thread completely than start second thread, after complete second thread than start third thread, Please help me!!
Here is my code:
public class wait {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("First Thread");
createtheard2();
}
public static void createtheard2() {
try {
System.out.println("Second Thread");
} catch(Exception error1) {
error1.printStackTrace();
}
createtheard3();
}
public static void createtheard3() {
try {
System.out.println("Third Thread");
} catch(Exception error1) {
error1.printStackTrace();
}
}
}
After complete first thread, than start second thread, after complete second thread, than start third thread, Please help me!! Thanks!!

Implement Runnable
public class ThreadDemo implements Runnable {
public void run() {
//Do this what you need
}
}
Use join to wait while thread will be completed.
Thread t1 = new Thread(new ThreadDemo());
// this will call run() function
t1.start();
// waits for this thread to die
t1.join();
Thread t2 = new Thread(new ThreadDemo());
// this will call run() function
t2.start();
// waits for this thread to die
t2.join();
From http://docs.oracle.com/javase/tutorial/essential/concurrency/join.html
t.join() causes the current thread to pause execution until t's
thread terminates.
In your case paused by join method invocation thread will be Main thread.

I think what you need is if task 1 (thread in your terms) success, run task2 else wait for task1. consider the following.
public class Process{
public static void runProcess1() {
boolean done = false;
do {
// make done=true after task1 is done
} while (done);
runProcess2();
}
public static void runProcess2() {
boolean done = false;
do {
// make done=true after task2 is done
} while (done);
runProcess3();
}
public static void main(String[] args) {
runProcess1();
}
}

As it was pointed out, using threads in this case does not make sense as you are executing tasks sequentially.
However, it is possible to have a single thread running at a time with SingleThreadExecutor
For example, you
Add your threads to a "todo list" (ArrayList will do the job)
Schedule a task (ExecutorService.execute())
Wait for the scheduled task to complete (Thread.join())
Drop the thread from the "todo list" tasks.remove(currentTask);
Pick the next task or go to step 7 if all has been finished
Go back to step 2
Kill the ExecutorService (ExecutorService.shutdown())
Alternatively, you could use ExecutorService.invokeAll() using a single thread executor.
You could even simply run the tasks directly in a loop, invoking start(), however, I'd really recommend against using concurrency where it is not a necessity.

Related

Any caveats to a runnable storing a reference to its own running thread?

I have a long running Runnable object and I wanted to provide a more graceful interrupt mechanism than having to call interrupt on the thread the object is running on.
The before code:
public class MyRunnable implements Runnable {
public void run() {
while(!Thread.currentThread().isInterrupted()) {
//do stuff
}
}
}
public class MyClass {
public static void main(String[] args) {
Runnable myRunnable = new MyRunnable();
Thread t = new Thread(myRunnable, "myRunnableThread");
t.start();
//do stuff
t.interrupt();
//do stuff
}
}
And the new code:
public class MyRunnable implements Runnable {
private Thread myThread = null;
public void run() {
myThread = Thread.currentThread();
while(!myThread.isInterrupted()) {
//do stuff
}
}
public void shutdown() {
if (myThread != null) {
myThread.interrupt();
//do other shutdown stuff
}
}
}
public class MyClass {
public static void main(String[] args) {
Runnable myRunnable = new MyRunnable();
Thread t = new Thread(myRunnable, "myRunnableThread");
t.start();
//do stuff
myRunnable.shutdown();
//do stuff
}
}
My question is, are there possible side effects or unknowns that holding a reference to your own thread, and providing limited access to that thread through public methods (as above) could cause? This is assuming that no-one ever calls the run() method directly, that it is always started from a new thread.
And I'm aware that I could use a volatile or atomic Boolean in the run() and shutdown() methods for communicating intent to shutdown, I'm more interested in learning than a solution. But solutions are still welcome!
For me your first approach is much better as less error prone and more "standard". But actually what you try to implement already exists (which proves that it makes sense and that it is not a bad practice but it is not easy to make it properly), it is called FutureTask, instead of shutdown you have cancel(boolean mayInterruptIfRunning) with true as value of mayInterruptIfRunning if you want to interrupt the thread running the task, I quote the javadoc:
Attempts to cancel execution of this task. This attempt will fail if
the task has already completed, has already been cancelled, or could
not be cancelled for some other reason. If successful, and this task
has not started when cancel is called, this task should never run. If
the task has already started, then the mayInterruptIfRunning
parameter determines whether the thread executing this task should be
interrupted in an attempt to stop the task.
For example:
// Task that will only sleep for 1 sec and print a message on interrupted
FutureTask<Void> myRunnable = new FutureTask<>(
new Callable<Void>() {
#Override
public Void call() throws Exception {
try {
System.out.println("Sleep");
Thread.sleep(1_000L);
} catch (InterruptedException e) {
System.out.println("Interrupted !!!");
throw e;
}
return null;
}
}
);
new Thread(myRunnable, "myRunnableThread").start();
// Wait long enough to make sure that myRunnableThread is sleeping
Thread.sleep(500L);
// Cancel the task and interrupt myRunnableThread
myRunnable.cancel(true);
Output:
Sleep
Interrupted !!!
It already has a reference:
Thread.currentThread()
From the javadoc:
Returns a reference to the currently executing thread object.

How does Java Threads work

I'm a Java learner, trying to understand Threads.
I was expecting output from my program below, in the order
Thread started Run Method Bye
But I get output in the order
Bye Thread started Run Method
Here is my code:
public class RunnableThread
{
public static void main(String[] args)
{
MyThread t1= new MyThread("Thread started");
Thread firstThread= new Thread(t1);
firstThread.start();
System.out.println("Bye");
}
}
class MyThread implements Runnable
{
Thread t;
String s= null;
MyThread(String str)
{
s=str;
}
public void run()
{
System.out.println(s);
System.out.println("Run Method");
}
}
In a multithreaded code there's no guarantee which thread will run in what order. That's in the core of multithreading and not restricted to Java. You may get the order t1, t2, t3 one time, t3, t1, t2 on another etc.
In your case there are 2 threads. One is main thread and the other one is firstThread. It's not determined which will execute first.
This is the whole point of Threads - they run simultaneously (if your processor has only one core though, it's pseudo-simultaneous, but to programmer there is no difference).
When you call Thread.start() method on a Thread object it's similar (but not the same, as it's starting a thread, and not a process and former is much more resource consuming) simultaneously starting another java program. So firstThread.start() starts to run paralel to your main thread (which was launched by your main method).
This line starts a main execution thread (like a zeroThread)
public static void main(String[] args)
Which you can reference, by calling Thread.sleep() for example.
This line
firstThread.start();
Starts another thread, but in order to reference it you use it's name, but you reference it from the main thread, which is running paralel to firstThread.
In order to get the expected output you can join these two threads, which is like chaining them:
This way:
public static void main(String[] args)
{
MyThread t1= new MyThread("Thread started");
Thread firstThread= new Thread(t1);
firstThread.start();
firstThread.join();
System.out.println("Bye");
}
join(), called on firstThread (by main thread) forces main thread to wait until the firstThread is finished running (it will suspend proceding to the next command, which is System.out.println("Bye");).
It appears that you seek the thread (and probably more than one) to run while main() waits for everything to finish up. The ExecutorService provides a nice way to manage this -- including the ability to bail out after a time threshold.
import java.util.concurrent.*;
class MyThread implements Runnable { // ... }
class MyProgram {
public static void main(String[] args)
{
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
MyThread t3 = new MyThread();
// At this point, 3 threads teed up but not running yet
ExecutorService es = Executors.newCachedThreadPool();
es.execute(t1);
es.execute(t2);
es.execute(t3);
// All three threads now running async
// Allow all threads to run to completion ("orderly shutdown")
es.shutdown();
// Wait for them all to end, up to 60 minutes. If they do not
// finish before then, the function will unblock and return false:
boolean finshed = es.awaitTermination(60, TimeUnit.MINUTES);
System.out.println("Bye");
}
}
There is no specified order in which Java threads are accustomed to run. This applies for all threads including the "main" thread.
If you really want to see it working, try:
class RunnableThread
{
public static void main(String[] args)
{
MyThread t1= new MyThread();
Thread firstThread= new Thread(t1);
firstThread.start();
System.out.println("Thread Main");
for(int i=1;i<=5;i++)
{
System.out.println("From thread Main i = " + i);
}
System.out.println("Exit from Main");
}
}
class MyThread implements Runnable
{
public void run()
{
System.out.println("Thread MyThread");
for(int i=1;i<=5;i++)
{
System.out.println("From thread MyThread i = " + i);
}
System.out.println("Exit from MyThread");
}
}
When You start a Thread it will execute in parallel to the current one, so there's no guarantee about execution order.
Try something along the lines:
public class RunnableThread {
static class MyThread implements Runnable {
Thread t;
String s= null;
MyThread(String str) {
s=str;
}
public void run() {
System.out.println(s);
System.out.println("Run Method");
}
}
public static void main(String[] args) {
MyThread t1= new MyThread("Thread started");
Thread firstThread= new Thread(t1);
firstThread.start();
boolean joined = false;
while (!joined)
try {
firstThread.join();
joined = true;
} catch (InterruptedException e) {}
System.out.println("Bye");
}
}
This is not a thread start order problem. Since you're really only starting a single thread.
This is really more of an API Call speed issue.
Basically, you have a single println() printing "bye", which gets called as soon as the Thread.start() returns. Thread.start() returns immediately after being called. Not waiting for the run() call to be completed.
So you're racing "println" and thread initializaiton after "thread.start()", and println is winning.
As a sidenote, and in general, you might want to try to use ExecutorService and Callable when you can, as these are higher level, newer APIs.

How to notify another thread

I want to know the best way how to notify another thread. For example, I have a background thread:
public void StartBackgroundThread(){
new Thread(new Runnable() {
#Override
public void run() {
//Do something big...
//THEN HOW TO NOTIFY MAIN THREAD?
}
}).start();
}
When it finished it has to notify main thread? If somebody knows the best way how to do this I'll appreciate it!
The typical answer is a BlockingQueue. Both BackgroundThread (often called the Producer) and MainThread (often called the Consumer) share a single instance of the queue (perhaps they get it when they are instantiated). BackgroundThread calls queue.put(message) each time it has a new message and MainThread calls 'queue.take()which will block until there's a message to receive. You can get fancy with timeouts and peeking but typically people want aBlockingQueueinstance such asArrayBlockingQueue`.
Purely based on your question you could do this:
public class test
{
Object syncObj = new Object();
public static void main(String args[])
{
new test();
}
public test()
{
startBackgroundThread();
System.out.println("Main thread waiting...");
try
{
synchronized(syncObj)
{
syncObj.wait();
}
}
catch(InterruptedException ie) { }
System.out.println("Main thread exiting...");
}
public void startBackgroundThread()
{
(new Thread(new Runnable()
{
#Override
public void run()
{
//Do something big...
System.out.println("Background Thread doing something big...");
//THEN HOW TO NOTIFY MAIN THREAD?
synchronized(syncObj)
{
System.out.println("Background Thread notifing...");
syncObj.notify();
}
System.out.println("Background Thread exiting...");
}
})).start();
}
}
and see this output
PS C:\Users\java> javac test.java
PS C:\Users\java> java test
Main thread waiting...
Background Thread doing something big...
Background Thread notifing...
Background Thread exiting...
Main thread exiting...
Just call notify()
public void run() {
try {
while ( true ) {
putMessage();
sleep( 1000 );
}
}
catch( InterruptedException e ) { }
}
private synchronized void putMessage() throws InterruptedException {
while ( messages.size() == MAXQUEUE )
wait();
messages.addElement( new java.util.Date().toString() );
notify();
}
You can't "notify the main thread".
The best approach is to use an ExecutorService, like this for example:
import java.util.concurrent.*;
// in main thread
ExecutorService executorService = Executors.newSingleThreadExecutor();
Future<?> future = executorService.submit(new Runnable() {
#Override
public void run() {
//Do something big...
}
});
future.get(); // blocks until the Runnable finishes
The classes are written specially to deal with asynchronous operations, and all the code in there is already written for you and bullet-proof.
Edit
If you don't want to block the main thread while waiting, wait within another thread:
final Future<?> future = executorService.submit(new Runnable() {
#Override
public void run() {
//Do something big...
}
});
new Thread(new Runnable() {
#Override
public void run() {
future.get(); // blocks until the other Runnable finishes
// Do something after the other runnable completes
}
}).start();
One thread notifying another thread is not a good way to do it. Its better to have 1 master thread that gives the slave thread work. The slave thread is always running and waits until it receives work. I recommend that you draw two columns and determine exactly where each thread needs to wait.
public void run()
{
//Do something big...
synchronized(this)
{
done = true;
}
}
Java includes libraries that make this really easy see ExecutorService and the following post
Producer/Consumer threads using a Queue

Thread Executor - beginner

I have two classes. In class A, I have the run() method looped forever, while in the class B, i have the threadpool.
My question is, From Class B, how can I control and stop the thread executing run() method in class A , I have tried forceshutdown, threadExecutor.shutdownNow(), But it isnt working.
The loop seems to go on forever.
Here is example piece of code:
public class A implements Runnable {
public void run() {
while (true) {
System.out.println("Hi");
}
}
}
public class B {
public static void main(String[] args) {
int noOfThreads = 1;
A ThreadTaskOne = new A();
System.out.println("Threads are being started from Class B");
ExecutorService threadExecutor = Executors.newFixedThreadPool(noOfThreads);
threadExecutor.execute(ThreadTaskOne);
threadExecutor.shutdownNow();
System.out.println("B Ends, no of threads that are alive : " + Thread.activeCount());
}
}
As #MadProgammer said, your "infinite" loop needs to pay attention to Thread.isInterrupted. e.g. (very schematic)
public void run() {
while (!Thread.isInterrupted()) {
doSomethinginTheLoop1();
blah...blah...blah
// if the loop is very long you might want to check isInterrupted
// multiple times for quicker termination response
doSomethingInTheLoop2();
}
// now, here's a decision of what you do
// do you throw an InterruptedException or trust others to check interrupted flag.
// read Java COncurrency in Practice or similar...
}
The documentation on ExecutorService#shutdownNow() says -
There are no guarantees beyond best-effort attempts to stop processing actively executing tasks. For example, typical implementations will cancel via Thread.interrupt(), so any task that fails to respond to interrupts may never terminate.
And your thread doesn't seem to care if it has been interrupted.
So check if it has been interrupted
while (Thread.currentThread().isInterrupted())
instead of just doing
while (true)
May be below is useful for you.
public static class A implements Runnable {
public void run() {
while (!Thread.currentThread().isInterrupted()) {
System.out.println("Hi");
}
}
}

Regarding assigning task to daemon thread

I have one requirement that I want to create a pool of 5 threads and now I want to make 1 thread out of those 5 threads as a daemon thread and when that particular 1 thread becomes as daemon thread , then I want to assign some task to that daemon thread related to any service such that when the java program exits I can check in window task manager that particular daemon thread is still doing that task., Please advise how to achieve that ..! As I am stuck up on this..!
below is my code...
public class StoppingThread extends Thread //extend thread class
{
// public synchronized void run()
//synchronized (this)
private volatile boolean Completed = false;
public void setCompleted() {
Completed = true;
}
public void run()
{
for(int i=0;i<20 && !Completed;++i) {
System.out.println(Thread.currentThread().getName());
try {
Thread.sleep(500);
System.out.print(i +"\n"+ "..");
} catch(Exception e) {
e.printStackTrace();
}
}
}
public static void main(String... a)
{
StoppingThread x = new StoppingThread();
StoppingThread y = new StoppingThread();
x.start();
x.setName("first");
x.setCompleted(); // Will complete as soon as the latest iteration finishes means bolean variable value is set to true
y.start();
y.setName("second");
}
}
Now in this I want to make Y thread as daemon thread and then want to assign some task to it
Use ShutDownHook. The Thread which you register into the hook will be called when the application ends. You can add all clean up codes(DB,Stream,Context etc..) or any custom feature in this thread run method.
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() { // clean up code like closing streams,DB etc }
});

Categories