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;
}
}
Related
In my project I have a chart which can turn into an animation depending on if we click Start or Stop button. I can make it start, but I don't know how to stop it. Method shutdownNow() gives no result. How can I do this? Here is my code
public class Animation extends JPanel{
// initializations
ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1);
Animation(String s){
// initialization of chart and adding XYSeries
this.add(chartPanel);
}
public void go() {
scheduler.scheduleAtFixedRate( (new Runnable() {
#Override
public void run() {
double first;
l = dataset.getSeries();
while(true) {
first = (double)l.get(0).getY(0);
for (int k = 0; k < l.get(0).getItemCount(); k++) {
if (k + 1 < l.get(0).getItemCount()) l.get(0).updateByIndex(k, l.get(0).getY(k+1));
else l.get(0).updateByIndex(k, first);
}
}
}
}), 0, 5, MILLISECONDS);
}
public void stop() {
scheduler.shutdownNow();
}
}
As per java docs how shutdownNow() works like below.
There are no guarantees beyond best-effort attempts to stop processing
actively executing tasks. For example, typical implementations will
cancel via {#link Thread#interrupt}, so any a task that fails to
respond to interrupts may never terminate.
So, it will set interrupted flag true, so you need to correctly manage the InterruptedException and / or explicitly check Thread.currentThread().isInterrupted(). You can use below code to stop your current running inputted thread.
while (!Thread.currentThread().isInterrupted()) {
// your code here
}
(!Thread.currentThread().isInterrupted())
may be a solution
but personally i would:
extract runner in method
stop runner by flipping a boolean
call scheduler.shutdownNow(); when needed (on close JPanel?)
example:
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
boolean running;
public void setup() {
scheduler.scheduleAtFixedRate(runner(), 0, 5, TimeUnit.MILLISECONDS);
}
private Runnable runner() {
return () -> {
while (running) {
try {
//DO YOUR STUFF HERE
System.err.println("RUNNING");
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
}
public void go() {
running = true;
}
public void stop() {
running = false ;
}
public void shutdown() {
scheduler.shutdownNow();
}
public static void main(String[] args) throws InterruptedException {
Demo tasks = new Demo();
tasks.setup();
for (int i = 1; i <= 5; i++) {
System.err.println("GO FOR IT " + i);
tasks.go();
Thread.sleep(2000);
tasks.stop();
Thread.sleep(1000);
}
tasks.shutdown();
}
package threadShareResource1;
public class NonSynchro1 {
private int sum = 0;
public static void main(String[] args) {
NonSynchro1 n = new NonSynchro1();
n.task();
System.out.println(n.getSum());
}
public synchronized void sumAddOne(){
sum++;
}
public void task(){
for (int i = 0; i < 100; i++) {
new Thread(new Runnable(){
#Override
public void run() {
sumAddOne();
}
}).start();
/* try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
} */
}
}
public int getSum() {
return sum;
}
}
Without the commented part of code, the program has data corruption, which is not 100 every time I run it. But I thought the synchronized keyword should acquires a lock on the sumAddOne method, which is the critical region of my program, allowing one thread accessing this method every time.
I've try to use ExecutorService as well, but it doesn't give 100 all the runs.
public void task(){
ExecutorService s = Executors.newCachedThreadPool();
for (int i = 0; i < 100; i++) {
s.execute(new Thread(new Runnable(){
#Override
public void run() {
sumAddOne();
}
}));
}
s.shutdown();
while(!s.isTerminated()){}
}
In Task(), you start 100 threads (which is a lot) and each one is to add 1 to sum.
But when Task is done all you know is that 100 threads are in some process of having started. You don't block before calling println(), so how do you know all the threads have completed?
The sleep probably "prevents the corruption" just because it gives the system time to finish launching all the threads.
Beyond that you are using Synchronized correctly. Any place multiple threads may write to the same variable you need it and, in general (simplifying), you don't need it if you are only reading.
Synchronised keyword is used correctly, the problem is that you are not waiting for the threads to finish. Here is a possible solution:
public class NonSynchro1 {
private static final ExecutorService executorService = Executors.newCachedThreadPool();
private int sum = 0;
public static void main(String[] args) {
NonSynchro1 n = new NonSynchro1();
n.task();
System.out.println(n.getSum());
executorService.shutdown();
}
public synchronized void sumAddOne() {
sum++;
}
public void task() {
List<Callable<Object>> callables = new ArrayList<>();
for (int i = 0; i < 100; i++) {
callables.add(() -> {
sumAddOne();
return null;
});
}
List<Future<Object>> futures;
try {
futures = executorService.invokeAll(callables);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
futures.forEach(future -> {
try {
future.get();
} catch (ExecutionException | InterruptedException e) {
throw new RuntimeException(e);
}
});
}
public int getSum() {
return sum;
}
}
First we create a list of callables - a list of functions that will be executed in parallel.
Then we invoke them on the executor service. newCachedThreadPool I have used here, by default has 0 threads, it will create as many as necessary to execute all passed callables, the threads will be killed after being idle for a minute.
Finally, in the for-each loop we resolve all futures. get() call will block until the function was executed by the executor service. It will also throw exception if it was thrown inside the function (without calling get() you would not see such exception at all).
Also, it is a good idea to shutdown the executor service when you want to terminate the program gracefully. In this case, it is just executorService.shutdown() at the end of main method. If you don't do this, the program will terminate after a minute when idle threads are killed. However, if different executor service, threads might not be killed when idle, in which case the program would never terminate.
Just for completeness sake: Here's a solution showing how the original program can be made to wait for all threads to finish by joining them:
for (Thread t : n.task())
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
which requires task to return the threads it creates. In this case we don't need to complicate things with caching managers or collections: a simple array will do. Here's the complete class:
public class TestSynchro1 {
private int sum = 0;
public synchronized void sumAddOne() {
sum++;
}
public Thread[] task(int n) {
Thread[] threads = new Thread[n];
for (int i = 0; i < n; i++) {
(threads[i] = new Thread(new Runnable() {
#Override
public void run() {
sumAddOne();
}
})).start();
}
return threads;
}
public static void main(String[] args) {
TestSynchro1 n = new TestSynchro1();
for (Thread t : n.task(100))
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(n.sum);
}
}
I have 10 different threads which I want to start at the same time. And by same time, I mean not by starting them sequentially (although this will be close).
What is the best way to achieve this in java?
To be accurate: You will not be able to start all 10 threads at the exact same time. There will be some difference in the order ms or ns. You can just try to minimize this difference. And even then: If you have less cores than threads the first couple of threads will have done some work before the others even run their first instruction.
There's a nice example of using a CountDownLatch for that in the Javaspecialists newsletter The Law of the Corrupt Politician.
public class TestCorruption {
private static final int THREADS = 2;
private static final CountDownLatch latch = new CountDownLatch(THREADS);
private static final BankAccount heinz = new BankAccount(1000);
public static void main(String[] args) {
for (int i = 0; i < THREADS; i++) {
addThread();
}
Timer timer = new Timer(true);
timer.schedule(new TimerTask() {
public void run() {
System.out.println(heinz.getBalance());
}
}, 100, 1000);
}
private static void addThread() {
new Thread() {
{
start();
}
public void run() {
latch.countDown();
try {
latch.await();
} catch (InterruptedException e) {
return;
}
while (true) {
heinz.deposit(100);
heinz.withdraw(100);
}
}
};
}
}
It depends on the number of cores your computer have, those will be the number of started threads on the same time, it is my first comment here so i hope this is correct.
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Practica {
private static final int NUMTHREADS = 10;
public static void main(String[] args) {
CountDownLatch cdl = new CountDownLatch(NUMTHREADS);
ExecutorService executor = Executors.newFixedThreadPool(NUMTHREADS);
for (int i = 0; i < NUMTHREADS; i++) {
executor.submit(new Imp(cdl));
cdl.countDown();
System.out.println("one thread sumbmited "+cdl.getCount());
}
System.out.println("All threads submmited");
executor.shutdown();
}
}
class Imp implements Runnable {
CountDownLatch cdl;
public Imp(CountDownLatch arg) {
this.cdl = arg;
}
#Override
public void run() {
try {
cdl.await();
System.out.printf("STARTED %s at %d millis%n",
Thread.currentThread().getName(),
System.currentTimeMillis());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
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");
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;
}
}
}