I have a multithreaded program where I want the one of the thread to print the statement after all the thread finished.How can I do that? and How do I know that all the threads finished?
ExecutorService pool = Executors.newCachedThreadPool();
for(int i = 0; i < myList.size(); ++i) {
pool.execute (new ThreadProcessRunnable (args));
}
public class ThreadProcessRunnable implements Runnable {
public void run() {
System.out.println("last thread should execute this");
}
}
That sounds like an ideal use case for ExecutorService.invokeAll:
ExecutorService pool = Executors.newCachedThreadPool();
List<Callable<Object>> tasks = new ArrayList<Callable<Object>>();
for(int i = 0; i < myList.size(); ++i) {
tasks.add (Executors.callable(new ThreadProcessRunnable (args)));
}
List<Future<Object>> futures = pool.invokeAll(tasks);
System.out.println("All tasks finished");
public class ThreadProcessRunnable implements Runnable {
public void run() {
// do some stuff
}
}
invokeAll blocks until all the tasks in the supplied List are complete.
If you absolutely must have the println inside one of the threads' run methods, then the simplest approach I can think of would be to keep some sort of counter in an AtomicInteger
public class ThreadProcessRunnable implements Runnable {
private AtomicInteger taskCounter;
public ThreadProcessRunnable(AtomicInteger counter) {
this.taskCounter = counter;
}
public void run() {
// do stuff
if(taskCounter.decrementAndGet() == 0) {
System.out.println("I am the last thread and I am about to finish");
}
}
}
// Main class
ExecutorService pool = Executors.newCachedThreadPool();
AtomicInteger taskCounter = new AtomicInteger(myList.size());
for(int i = 0; i < myList.size(); ++i) {
pool.execute(new ThreadProcessRunnable(taskCounter));
}
The key thing that makes this work is that taskCounter.decrementAndGet is atomic - if the value of taskCounter is initially 2, for example, and two different threads call decrementAndGet at the same time then it is guaranteed that one thread will see the value 1 and the other thread will see the value 0, so exactly one thread will print the "about to finish" message. This is different from MadProgrammer's answer, which involves a race condition:
latch.countDown();
if(latch.getCount() == 0) { ... }
where it is possible to have thread 1 decrement the value (to 1), then thread 2 decrement it again (to 0), then both threads see the value 0 when they call getCount and both print the message.
This is a REALLY basic example/concept of using a CountDownLatch
public class TestCountDownLatch {
private static CountDownLatch latch;
public static void main(String[] args) {
latch = new CountDownLatch(10);
ExecutorService pool = Executors.newCachedThreadPool();
for (int i = 0; i < 10; ++i) {
pool.execute(new Worker(i));
}
}
public static class Worker implements Runnable {
private int number;
public Worker(int number) {
this.number = number;
}
#Override
public void run() {
try {
System.out.println(number + " is sleeping...");
Thread.sleep((long) (Math.round(Math.random() * 1000)));
} catch (InterruptedException ex) {
}
System.out.println(number + " is Completed...");
latch.countDown();
if (latch.getCount() == 0) {
System.out.println(number + " was last...");
}
}
}
}
Simple Single Thread Test Case
public class TestCountDownLatch {
private static CountDownLatch latch;
public static void main(String[] args) {
latch = new CountDownLatch(1);
ExecutorService pool = Executors.newCachedThreadPool();
for (int i = 0; i < 1; ++i) {
pool.execute(new Worker(i));
}
}
public static class Worker implements Runnable {
private int number;
public Worker(int number) {
this.number = number;
}
#Override
public void run() {
try {
System.out.println(number + " is sleeping...");
Thread.sleep((long) (Math.round(Math.random() * 1000)));
} catch (InterruptedException ex) {
}
System.out.println(number + " is Completed...");
latch.countDown();
if (latch.getCount() == 0) {
System.out.println(number + " was last...");
}
}
}
}
You can use a CyclicBarrier with a barrier action (documentation).
Creates a new CyclicBarrier that will trip when the given number of
parties (threads) are waiting upon it, and which will execute the
given barrier action when the barrier is tripped, performed by the
last thread entering the barrier.
You can place it in the main thread. Call pool.await() to block the main thread until all threads in the pool have finished, then do the extra work. The code would look like this:
ExecutorService pool = Executors.newCachedThreadPool();
for(int i = 0; i < myList.size(); ++i) {
pool.execute (new ThreadProcessRunnable (args));
}
pool.shutdown();
pool.awaitTermination();//blocks the main thread
System.out.println("last thread should execute this");
Related
Does CyclicBarrier best suitable, in this case.
I want to run n threads parallel in Stages (wait at Stages until all threads completes that Stage).
public class CyclicBarr {
public static void main(String[] args) {
CyclicBarrier barrier = new CyclicBarrier(3, new Runnable() {
private int count =1;
#Override
public void run() {
System.out.println("Completed..!! "+(count++));
}
});
for (int i = 1; i <= 3; i++) {
Thread t = new Thread(new CuclicBarThread(barrier));
t.start();
}
}
}
And Thread is
public class CuclicBarThread implements Runnable {
CyclicBarrier barrier;
public CuclicBarThread(CyclicBarrier barrier) {
this.barrier = barrier;
}
#Override
public void run() {
try {
for (int i = 1; i < 5; i++) {
Thread.sleep(100);
}
System.out.println(Thread.currentThread().getName() + " :: Waiting At Barrier 1 After Stage 1 Completed");
barrier.await();
for (int i = 1; i < 5; i++) {
Thread.sleep(1000);
}
System.out.println(Thread.currentThread().getName() + " :: Waiting At Barrier 2 After Stage 2 Completed");
barrier.await();
for (int i = 1; i < 5; i++) {
Thread.sleep(100);
}
System.out.println(Thread.currentThread().getName() + " :: Waiting At Barrier 3 After Stage 3 Completed");
barrier.await();
System.out.println(Thread.currentThread().getName()+" :: $$$$$$$$ Completed $$$$$$$$");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Yes it is reusable. That is why it is called "Cyclic". Here is the quote from its JavaDoc:
A synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point. CyclicBarriers are useful in programs involving a fixed sized party of threads that must occasionally wait for each other. The barrier is called cyclic because it can be re-used after the waiting threads are released.
And your usage of the CyclicBarrier seems fine to me.
main thread creating two thread t1 and t2 run() method of these thread creating two new thread c1 and c2.I want a scenario such that until c1&c2(of t1) are alive t2 will not start executing.
In my code notify and wait are causing Runtime Exception.Since they are not in synchronised block, how to do this?
public class childTcreat2newthread {
public static void main(String[] args) throws InterruptedException {
Thread mainT=Thread.currentThread();
Target ra=new Target("a");
Thread t1=new Thread(ra);
t1.start();
t1.join();
while(ra.getC1().isAlive()==true||ra.getC2().isAlive()==true){
synchronized (mainT) {
mainT.wait();
}}
new Thread(new Target("b")).start();}}
class Target implements Runnable{
Thread c1=new Thread(new Target1("1"));
Thread c2=new Thread(new Target1("2"));
String msg;
Target(String msg){
this.msg=msg;
}
#Override
public void run() {
for(int j=0;j<100000;j++){
for(int i=0;i<10000;i++){
if(i%10000==0&&j%10000==0){System.out.print(msg);}
}}
t1.start();
t2.start();
}
public Thread getC1(){return c1;}
public Thread getC2(){return c2;}
}
class Target1 implements Runnable {
String msg;
Target1(String msg){
this.msg=msg;
}
#Override
public synchronized void run() {
for(int j=0;j<100000;j++){
for(int i=0;i<100000;i++){
if(i%100000==0&&j%10000==0){System.out.print(msg);}
}
}
try{
notifyAll();
System.out.println("K");}catch(IllegalMonitorStateException e){System.out.println("\nIllegalMonitorStateException!! in "+msg+"\n");}
}
}
wait( ) tells the calling thread to give up the monitor and go to sleep until some others thread enters the same monitor and calls notify( ).Unable to get same monitor when calling notify.How to do this?
As for my understanding both the thread t1 & t2 does not have common object here to which these are accessing so which object we should have to pass in synchronised lock to call wait() and notify()?
as #JB Nizet pointed out you should use join to wait fot thread termination
EDIT
since you cannot use join I suggest you to use a CountDownLatch since
its documentation states:
A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.
Which is what you asked for.
SECOND EDIT
Here is a modified version of your code that wait for thread termination using a HomeMade CountDownLatch that uses wait and notify.
import java.util.concurrent.CountDownLatch;
public class childTcreat2newthread {
public static void main(String[] args) throws InterruptedException {
MyCountDownLatch doneSignal = new MyCountDownLatch(2);
Target ra = new Target("a",doneSignal);
Thread t1 = new Thread(ra);
t1.start();
doneSignal.await();
System.out.println("after await ");
MyCountDownLatch doneSignal1 = new MyCountDownLatch(2);
new Thread(new Target("b",doneSignal1)).start();
}
}
class Target implements Runnable {
private Thread c1;
private Thread c2;
String msg;
Target(String msg, MyCountDownLatch doneSignal) {
this.msg = msg;
c1 = new Thread(new Target1("1",doneSignal));
c2 = new Thread(new Target1("2",doneSignal));
}
#Override
public void run() {
System.out.println("Start of Target " + msg);
for (int j = 0; j < 100000; j++) {
for (int i = 0; i < 10000; i++) {
if (i % 10000 == 0 && j % 10000 == 0) {
System.out.print(msg);
}
}
}
c1.start();
c2.start();
// try {
// c1.join();
// c2.join();
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
System.out.println("End of Target " + msg);
}
public Thread getC1() {
return c1;
}
public Thread getC2() {
return c2;
}
}
class Target1 implements Runnable {
String msg;
private MyCountDownLatch doneSignal;
Target1(String msg, MyCountDownLatch doneSignal) {
this.msg = msg;
this.doneSignal=doneSignal;
}
#Override
public void run() {
System.out.println("Start of Target1 " + msg);
for (int j = 0; j < 100000; j++) {
for (int i = 0; i < 100000; i++) {
if (i % 100000 == 0 && j % 10000 == 0) {
System.out.print(msg);
}
}
}
try {
System.out.println("K");
doneSignal.countDown();
System.out.println("End of Target1 " + msg);
} catch (IllegalMonitorStateException e) {
System.out.println("\nIllegalMonitorStateException!! in " + msg
+ "\n");
}
}
}
class MyCountDownLatch {
private int waitersNum;
public MyCountDownLatch(int waitersNum) {
this.waitersNum=waitersNum;
}
public synchronized void countDown() {
waitersNum--;
if (waitersNum==0) {
notifyAll();
}
}
public synchronized void await() throws InterruptedException {
wait();
}
}
notify, notifyAll, wait calls should be done in the monitor of the same object. There should be a shared object like Object and you should build your logic around that. For example :
public class ClassA{
Object lockObject=new Object();
//Thread A will call this method
public void methodA(){
synchronized(lockObject){
while(!aCondition)
lockObject.wait();
}
}
//Thread B will call this method
public void methodB(){
synchronized(lockObject){
aCondition=true;
lockObject.notify();
}
}
}
In Java you can use Thread.join() to wait for a thread to exit
Is there a similar method that will allow you to wait for any thread in a list of threads to exit?
This would be similar to the wait(2) Unix system call that returns when any child process exits.
You could use a CountDownLatch from the java.util.concurrent package. Something like this:
CountDownLatch c = new CountDownLatch(3);
...
c.await();
Look at CountDownLatch if you are using Java 1.5 or above
Suppose you need to submit a set of background tasks, and you want to wait for each one to become available and process its result, but you don't want to block waiting for all of them before you start processing. You can use an ExecutorCompletionService.
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
public final class Main {
public static void main(String[] args) throws Exception {
// Bootstrap CompletionService backed by a pool of 5 daemon threads.
CompletionService<Integer> cs = new ExecutorCompletionService<Integer>(
Executors.newFixedThreadPool(5, new ThreadFactory() {
#Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setDaemon(true);
return t;
}
}));
// Submit 20 contrived Callables that just return a monotonically
// increasing integer. Introduce a random sleep just to make the
// multi-threading effects more visible.
int n = 20;
for (int i = 0; i < n; ++i) {
final Integer result = i;
// The submit call does not block here.
cs.submit(new Callable<Integer>() {
#Override
public Integer call() {
try {
Thread.sleep((long)(Math.random() * 10));
return result;
} catch (InterruptedException e) {
return null;
}
}
});
}
for (int i = 0; i < n; ++i) {
// The take call blocks here until the next Callable finishes.
Integer result = cs.take().get();
if (result != null) {
System.out.println(result);
}
}
}
}
CountdownLatch is nice, but a Semaphore is re-useable.
final Semaphore semaphore = new Semaphore(0);
class WaitedForTask implements Runnable {
#Override
public void run() {
try {
doSomethingUseful();
} finally {
semaphore.release();
}
}
}
void runnem() throws InterruptedException {
Thread[] thread = new Thread[NUMTHREADS];
for (int i=0 ; i<NUMTHREADS ; i++) {
thread[i] = new Thread(new WaitedForTask());
thread[i].start();
}
for (int i=0 ; i<NUMTHREADS ; i++) {
semaphore.acquire();
System.out.println("Another one bites the dust.");
}
}
I want to build an application that executes a certain utility with multi threads. I want to control the amount of threads. Here is what I want to do:
//initialize the number of threads to be 10
for(int i = 0; i < BIG_VALUE; i++) {
RunnableObject rb = new RunnableObject(i);
rb.run();
//the for loop should run for 10 loops. When one of the threads finish its job
//the for loop continues and runs another thread. The amount of threads should
//always be 10
}
How can I do so in Java?
You can try with Java Executor framework http://docs.oracle.com/javase/tutorial/essential/concurrency/executors.html
Here an example of how to used
public class SimpleThreadPool {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
Runnable worker = new WorkerThread('' + i);
executor.execute(worker);
}
executor.shutdown();
while (!executor.isTerminated()) {
}
System.out.println('Finished all threads');
}
}
public class WorkerThread implements Runnable {
private String command;
public WorkerThread(String s){
this.command=s;
}
#Override
public void run() {
System.out.println(Thread.currentThread().getName()+' Start. Command = '+command);
processCommand();
System.out.println(Thread.currentThread().getName()+' End.');
}
private void processCommand() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
#Override
public String toString(){
return this.command;
}
}
I am trying to create multiple threads, the number of which is dependent on the input from the command line. I know extending Thread isn't the best OO practice unless you are making a specialized version of Thread, but hypothetically is this code creating the desired result?
class MyThread extends Thread {
public MyThread (String s) {
super(s);
}
public void run() {
System.out.println("Run: "+ getName());
}
}
class TestThread {
public static void main (String arg[]) {
Scanner input = new Scanner(System.in);
System.out.println("Please input the number of Threads you want to create: ");
int n = input.nextInt();
System.out.println("You selected " + n + " Threads");
for (int x=0; x<n; x++)
{
MyThread temp= new MyThread("Thread #" + x);
temp.start();
System.out.println("Started Thread:" + x);
}
}
}
You have better alternative with ExecutorService
Sample code:
import java.util.concurrent.*;
public class ExecutorTest{
public static void main(String args[]){
int numberOfTasks = Integer.parseInt(args[0]);
ExecutorService executor= Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
try{
for ( int i=0; i < numberOfTasks; i++){
executor.execute(new MyRunnable(i));
}
}catch(Exception err){
err.printStackTrace();
}
executor.shutdown(); // once you are done with ExecutorService
}
}
class MyRunnable implements Runnable{
int id;
public MyRunnable(int i){
this.id = i;
}
public void run(){
try{
System.out.println("Runnable started id:"+id);
System.out.println("Run: "+ Thread.currentThread().getName());
System.out.println("Runnable ended id:"+id);
}catch(Exception err){
err.printStackTrace();
}
}
}
Usage:
java ExecutorTest 2
Runnable started id:0
Run: pool-1-thread-1
Runnable ended id:0
Runnable started id:1
Run: pool-1-thread-2
Runnable ended id:1
Related posts: ( Advantages of using ExecutorService as a replacement for plain Thread)
ExecutorService vs Casual Thread Spawner
How to properly use Java Executor?
Yes, it is creating and starting n threads, all ending immediately after printing Run: and their name.
One important thing java JVM can create 20000 thread at a time .
Creating 255 threads in java
class MyThread1 extends Thread {
int k;
public MyThread1(int i) {
k = i;
}
#Override
public void run() {
//Your Code
System.out.println("Thread no. "+k);
}
}
class MainClass {
public static void main(String arg[]) throws UnknownHostException {
Refresh() ;
}
public static void Refresh(){
//create 255 Thread using for loop
for (int x = 0; x < 256; x++) {
// Create Thread class
MyThread1 temp = new MyThread1(x);
temp.start();
try {
temp.join(10);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Another simple example using ExecutorService as recommended by #ravindra-babu
class MyRunnable implements Runnable{
int id;
public MyRunnable(int i){
this.id = i;
}
public void run(){
try{
long init = System.currentTimeMillis();
System.out.println("Start of Thread ID = " + id);
Thread.sleep(id * 1000);
long end = System.currentTimeMillis();
long elapsedTime = end - init;
System.out.println("Elapsed time of Thread ID " + id + ": " + elapsedTime);
} catch(Exception err){
err.printStackTrace();
}
}
}
Then all you need to do is create a new Thread inside the loop
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
try{
ExecutorService executor= Executors.newFixedThreadPool(1);
executor.execute(new MyRunnable(i));
executor.shutdown();
} catch(Exception err){
err.printStackTrace();
return;
}
}
}