This question already has answers here:
Run Java Threads sequentially
(13 answers)
Closed 9 years ago.
how to Execute threads sequentially ? (e.g i have 3 threads T1,T2,T3 and i want to start these threads same time but ensure that they should run sequentially one after other like first T1 then T2 and at last T3.)
Thread t1= new Thread(new Runnable()
{
void run()
{System.out.println("inside Thread1");}
});
Thread t2= new Thread(new Runnable()
{
void run()
{System.out.println("inside Thread2");}
});
Thread t3= new Thread(new Runnable()
{
void run()
{System.out.println("inside Thread3");}
});
t1.start();
t2.strat();
t3.start();
output:
inside Thread1
inside Thread2
inside Thread3
each time u run o/p should be as shown above.
In my humble opinion, you perhaps do not need threads, just call T1(), T2(), T3() methods sequentially in your code?
Threads are used to run multiple tasks in parallel.
You can synchronize these threads through flag/s. You can also use inbuilt synchronizers provided by Java like BlockingQueue.
Use BlockingQueues to synchronize the threads
final BlockingQueue q1 = new SynchronousQueue();
final BlockingQueue q2 = new SynchronousQueue();
Thread t1 = new Thread() {
public void run() {
...
try {
q1.put(new Object());
} catch (InterruptedException e) {
}
};
};
Thread t2 = new Thread() {
public void run() {
try {
q1.take();
...
q2.put(new Object());
} catch (InterruptedException e) {
}
}
};
Thread t3 = new Thread() {
public void run() {
try {
q2.take();
...
} catch (InterruptedException e) {
}
}
};
t1.start();
t2.start();
t3.start();
Threads are used to run multiple tasks at a same time.
In your case you need different methods called sequentially rather than Threads.
You should use:
class Methods_Than_Threads{
void T1()
{
//something
}
void T2()
{
//something
}
void T3()
{
//something
}
public static void main(String []args)
{
T1();//First T1
T2();//Second T2
T3();//Third T3
}
}
You should separate the actual tasks from how they are executed. I.e. don't extend Thread and overwrite run, instead implement Runnable as the task and don't care about the way it is executed.
That way you can design (+change later) the way you execute tasks independently from the actual implementation of a task.
E.g. Call each .run() directly if you want to execute them after each other or let some Executor handle them or even run them via new Thread manually.
If they have to wait on each other you could also use a Future. For example:
class ProcessingChainElement implements Callable<String> {
private final Future<String> previous;
public ProcessingChainElement(Future<String> previousResult) {
previous = previousResult;
}
#Override
public String call() throws Exception {
// prepare something that may take some time but does not depend on
// any previous result
Thread.sleep(500);
// get result from previous task, this blocks until it is available
result = previous.get() + " [" + System.currentTimeMillis() + "]";
return result;
}
}
And build a chain of tasks that can be executed in any way you want.
ExecutorService executor = Executors.newFixedThreadPool(3);
Future<String> result1 = executor.submit(...
Future<String> result2 = executor.submit(new ProcessingChainElement(result1));
...
Result is that each task can wait on results of a previous task but may very well run in parallel if there is anything that can be run in parallel.
Example http://ideone.com/VAg8q3 demonstrates that 3 tasks that take >= 500ms each and depend on each other could be done much quicker than actually running them in sequence.
Related
I would like to execute 3 methods at same time in Java (obviously I need threads), and that I would like to execute not in separate class and not in my main method, but in my custom method. Can it be done?
I have find this piece of code - Execute Multiple Methods Simaltaneously Using Thread In Java
and reused best marked answer for my example, with parameters that I have:
private void fetchData() {
boolean t1_run = true;
boolean t2_run = true;
boolean t3_run = true;
int SLEEP_TIME = 100;//Configurable.
Thread thread1 = new Thread() {
public void run() {
while (t1_run)
{
try
{
subjects = new BeanItemContainer<KltSubject>(KltSubject.class, clijentService.getSubjecteByType(Integer.valueOf(creditor)));
Thread.sleep(SLEEP_TIME);//So that other thread also get the chance to execute.
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
};
Thread thread2 = new Thread() {
public void run() {
while (t2_run)
{
try
{
programs = new BeanItemContainer<Program>(Program.class, creditService.getAllPrograms());
Thread.sleep(SLEEP_TIME);//So that other thread also get the chance to execute.
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
};
Thread thread3 = new Thread() {
public void run() {
while (t3_run)
{
try
{
credits = new BeanItemContainer<CreditExt>(CreditExt.class, creditService.getAllCredits());
Thread.sleep(SLEEP_TIME);//So that other thread also get the chance to execute.
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
};
thread1.start();
thread2.start();
thread3.start();
}
Now, before I've put my variables in threads (variables named: subjects, programs and credits), I could easily get their values (these variables you can see in above code in this example in their run methods, but are defined outside my fetchData() method and are visible).
After setting code like this, and executing it, I recieve null pointer exception because obviously varaibles are not seen any more after threads are executed. How to get that values after execution in threads?
P.S. can this code be written more elegantly, with less lines of code? If Java 8 (or Java 7) can done it - show me please how?
Use advanced Threading API : ExecutorService invokeAll()
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
throws InterruptedException
Executes the given tasks, returning a list of Futures holding their status and results when all complete. Future.isDone() is true for each element of the returned list. Note that a completed task could have terminated either normally or by throwing an exception. The results of this method are undefined if the given collection is modified while this operation is in progress.
Sample code:
ExecutorService service = Executors.newFixedThreadPool(3);
List<MyCallable> futureList = new ArrayList<MyCallable>();
MyCallable1 myCallable1 = new MyCallable1(); // your first thread
MyCallable2 myCallable2 = new MyCallable2(); // your second thread
MyCallable3 myCallable1 = new MyCallable3(); // your third thread
futureList.add(myCallable1);
futureList.add(myCallable2);
futureList.add(myCallable3);
System.out.println("Start");
try{
List<Future<Long>> futures = service.invokeAll(futureList);
for(Future<Long> future : futures){
try{
System.out.println("future.isDone = " + future.isDone());
System.out.println("future: call ="+future.get());
}
catch(Exception err1){
err1.printStackTrace();
}
}
}catch(Exception err){
err.printStackTrace();
}
service.shutdown();
You can have a look into few more examples in this article
You can use join() to wait for the threads to finish.
eg:
thread1.join();
thread2.join();
thread3.join();
when all the threads are done, the variables shouldn't be null.
Making this more compact depends on what exactly you're trying to do. Here is an example:
private List<Result> fetchData() {
final List<Result> results = new ArrayList<Result>();
List<Thread> threads = new ArrayList<Thread>();
for(int i = 0; i < 3; i++){
Thread t = new Thread() {
public void run() {
Result result = getResult();
synchronized(results) {
results.add(result);
}
}
};
t.start();
threads.add(t);
}
for(Thread t:threads) {
t.join();
}
return results;
}
You can simply use a CompletableFuture:
CompletableFuture<BeanItemContainer<KltSubject>> job1 = CompletableFuture.supplyAsync(() ->
new BeanItemContainer<>(KltSubject.class, clijentService.getSubjecteByType(creditor)));
CompletableFuture<BeanItemContainer<Program>> job2 = CompletableFuture.supplyAsync(() ->
new BeanItemContainer<>(Program.class, creditService.getAllPrograms()));
CompletableFuture<BeanItemContainer<CreditExt>> job3 = CompletableFuture.supplyAsync(() ->
new BeanItemContainer<>(CreditExt.class, creditService.getAllCredits()));
subjects = job1.join();
programs = job2.join();
credits = job3.join();
The method supplyAsync will initiate the asynchronous computation of a value and join will return the computed value, waiting, if necessary. But if all three actions imply querying the same database, it might be possible, that you don’t gain any performance advantage as the database may be the limiting factor.
For this below program, the ans is --> print : printName , then wait for 5 seconds then print : printValue
But as far as I know that its up to JVM to pick a thread and start its run method. So why it cannot be (printvalue printname and then 5 sec pause).
Note : I understand the conept of synchornized method but how we are sure here that JVM will always pick the thread t1 as its first thread.
class B {
public synchronized void printName() {
try {
System.out.println("printName");
Thread.sleep(5 * 1000);
} catch (InterruptedException e) {
}
}
public synchronized void printValue() {
System.out.println("printValue");
}
}
public class Test1 extends Thread {
B b = new B();
public static void main(String argv[]) throws Exception {
Test1 t = new Test1();
Thread t1 = new Thread(t, "t1");
Thread t2 = new Thread(t, "t2");
t1.start();
t2.start();
}
public void run() {
if (Thread.currentThread().getName().equals("t1")) {
b.printName();
} else {
b.printValue();
}
}
}
In this context, the synchronize just means that they can't run at the same time, not that they have to run in order. If you want them to run in order, then you don't want threads, or you want a more sophisticated queuing mechanism.
So, you are correct in that the it could either be "printName" pause "printValue" or "printValue" "printName" pause.
If you run the program multiple times, you'll likely see the first one more frequently. You will see the second output occasionally. The skew is because there is a slight delay between the start() on thread 1 and start() on thread 2.
how we are sure here that JVM will always pick the thread t1 as its first thread.
You can never be sure that the t1 thread will start running before the t2 thread starts running. If you need the t1 thread to do something before the t2 thread does some other thing, then you will have to use some synchronization object (e.g., a Semaphore) to make t2 wait.
Semaphore semaphore = new Semaphore(0);
Thread t1 = new Thread(new Runnable() {
#Override
public void run() {
doTheThingThatHasToBeDoneFirst();
semaphore.release();
doOtherStuff();
}
}).start();
Thread t2 = new Thread(new Runnable() {
#Override
public void run() {
semaphore.acquire(); //will not return until t1 thread calls release().
doOtherOtherStuff();
}
}).start();
But that is not really a smart way to use threads. Why not just do this instead?
doTheThingThatHasToBeDoneFirst();
Thread t1 = new Thread(new Runnable() {
#Override
public void run() {
doOtherStuff();
}
}).start();
Thread t2 = new Thread(new Runnable() {
#Override
public void run() {
doOtherOtherStuff();
}
}).start();
As a rule of thumb, the more synchronization you have between your threads, the less benefit you get from using threads. If you want certain things to happen in a certain order, you should do those things in that order in a single thread.
The trick to using threads is to design your program so that there are useful things it can do where order does not matter.
This question already has answers here:
How to properly stop the Thread in Java?
(9 answers)
Closed 9 years ago.
I am having a problem trying to stop a thread instantly after a certain amount of time has elapsed, because thread.stop and similar others have been depreciated.
The thread that I am trying to stop uses my mouse and I need to stop it so that I can use my mouse in other ways.
What I was thinking is the code below, which was just to make another thread to watch how long the main thread has been running and if it is alive, stop it, but I can't accomplish this.
public void threadRun(int a) {
Thread mainThread = new Thread(new Runnable() {
#Override
public void run() {
// does things with mouse which may need to be ended while they
// are in action
}
});
Thread watchThread = new Thread(new Runnable() {
#Override
public void run() {
if (timeFromMark(mark) > a) {
if (mainThread.isAlive()) {
// How can I stop the mainThread?
}
}
}
});
}
You need to define a class for your second thread that extends runnable and pass the first thread as an argument.
Then you can stop the first thread.
But instead of doing this manually, have a look at the Java ThreadPoolExecuter and its awaitTermination(long timeout, TimeUnit unit) method. (http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ThreadPoolExecutor.html )
Will save a lot of work.
ExecutorService executor = Executors.newFixedThreadPool(1);
Runnable r = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
System.out.println("doing stuff");
Thread.sleep(10000);
System.out.println("finished");
} catch (InterruptedException e) {
System.out.println("Interrupted before finished!");
}
}
};
executor.execute(r);
executor.shutdown();
try {
executor.awaitTermination(1, TimeUnit.SECONDS);
executor.shutdownNow();
} catch (InterruptedException e) {
//
}
System.out.println("Thread worker forced down. Continue with Application...");
Produces:
doing stuff
Interrupted before finished!
Thread worker forced down. Continue with Application...
Last two messages are nearly equal in terms of time and may change positions (its two different threads, continuing)
Java has deprecated methods for explicitly killing another thread (like Thread.stop / Thread.destroy). The right way is to make sure the operations on the other thread can handle being told to stop (for example, they expect an InterruptedException, which means you can call Thread.interrupt() in order to stop it).
Taken from How do I kill a thread from another thread in Java?
Killing/stopping threads is a bad idea. That's why they deprecated those methods. It's better to ask the thread to stop. E.g., something like the example below. (But note: if "do_something()" takes a long time, then you might want to use an interrupt to abort whatever it is.)
import java.util.concurrent.atomic.AtomicBoolean;
public class Stoppable {
private AtomicBoolean timeToDie = new AtomicBoolean(false);
private Thread thread;
public void start() {
if (thread != null) {
throw new IllegalStateException("already running");
}
thread = new Thread(new Runnable() {
public void run() {
while (!timeToDie.get()) {
// do_something();
}
}
});
thread.start();
}
public void stop() throws InterruptedException {
timeToDie.set(true);
thread.join();
thread = null;
}
}
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
I am trying to write a part of a multithreaded program where each thread from a fixed thread pool tries to fetch an object from a Queue and if the Queue is empty the thread waits.
The problem I am experiencing is that the memory used by the program keeps increasing.
public class Ex3 {
public static LinkedBlockingQueue<Integer> myLBQ = new LinkedBlockingQueue<Integer>(10);
public static void main(String argc[]) throws Exception {
ExecutorService executor = Executors.newFixedThreadPool(3);
myLBQ.add(new Integer(1));
for (;;) {
executor.execute(new MyHandler(myLBQ));
}
}
}
class MyHandler implements Runnable {
LinkedBlockingQueue<Integer> myLBQ;
MyHandler(LinkedBlockingQueue<Integer> myLBQ) {
this.myLBQ = myLBQ;
}
public void run() {
try {
myLBQ.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
I don't understand why the executor.execute keeps firing when the threads should be waiting for an item to be added to the Queue. How do I modify my code to reflect this?
This adds tasks to the executor as fast as it can.
for (;;) {
executor.execute(new MyHandler(myLBQ));
}
This will consume about 200 MB per second. It doesn't have anything to do with whether there are tasks to perform or not.
If you don't want to do this I suggest you move the loop to the runnable and add only one. This will cause it to wait for tasks forever.
A better approach is to use the ExecutorService's builtin queue to queue tasks.
ExecutorService executor = Executors.newFixedThreadPool(3);
final int taskId = 1;
executor.submit(new Runnable() {
#Override
public void run() {
doSomething(taskId);
}
});
executor.shutdown();
This does the same thing, but is much simpler IMHO.
it's because you're creating a gazillion instances of MyHandler and inserting them in the internal queue of the executor.
That infinite for loop is quite mean.