Execute a same action multiple times in parallel and looping on it - java

I'm trying introduce myself to parallel programming but I'm not sure I'm thinking the right way. I have multiple instances of a same class which I want to execute a same task simultaneously. After this, the threads wait for x time and perform the action again.
I currently thought about something like this
public class RunnableT implements Runnable {
#Override
public void run() {
while(!Main.stop) {
//Perform task
//Wait to mask next action
}
}
}
And so I would have a main thread like that:
public class Main {
public static boolean stop;
public static void main(String[] args) {
stop = false;
Thread t1 = new Thread(new RunnableT());
t1.start();
Thread t2 = new Thread(new RunnableT());
t2.start();
for(int i = 0; i < 10; i++) {
//Call t1 & t2 to perform the action
//Wait a second
//Loop
}
stop = true;
}
}
I know I'm doing it wrong but I can't figure out how I'm supposed to do it.

You cannot Call t1 & t2 to perform the action. Usually interaction between threads is done using (synchronized) queues, the best candidate is ArrayBlockingQueue. Create ArrayBlockingQueue in the main class, let the main thread put tasks in it, and let worker threads read from it and perform tasks.
UPDT. If you want each task be executed by each thread, then create 2 queues, one for each thread, and let each thread read only its own thread, while main thread creates next task and put it in both threads.

Related

Thread execution after .start() method

I am wondering what happens in the following scenario:
Two threads are created:
Thread t1 = new Thread();
Thread t2 = new Thread();
Assume these just print out a string, the threads then call the .start() method:
t1.start();
t2.start():
My question is why do these threads print in a seemingly random order each time? I know threads execute concurrently but would t1 not always finish before t2 due to the sequential execution of the main process?
Calling start() on a Thread doesn't necessarily result in the thread running immediately after. It is possible for other things to happen in between your calling start() and the first line of your thread's run() method actually being run. And even once your run() is actually running, it's also possible that other things happen before, during, or after your run() method finishes.
In your question, you said: "assume these just print out a string" – here's an implementation of run() which does that:
public void run() {
System.out.println("my name is: " + getName());
}
So it's possible that t1 starts to run first, but before it actually calls System.out.println, t2 is allowed to execute and runs to completion, then t1 is resumed.
If this kind of behavior won't work for your use case, you'll need to add some kind of concurrency protection to coordinate how and when your threads run.
UPDATE:
To illustrate the unpredictable sequence of thread execution, run this code a few times and observe the output:
public class Example {
public static void main(String[] args) {
for (int k = 0; k < 10; k++) {
new TestThread(k).start();
}
}
}
class TestThread extends Thread {
private final int k;
TestThread(int k) {
this.k = k;
}
#Override
public void run() {
System.out.print(k + " ");
}
}
Here is the output from one of my local runs:
7 0 1 5 4 6 3 2 8 9
Thread.start() doesn't guarantee execution. It will just make the Thread state runnable and hand over to the Thread Scheduler. It is the Thread Scheduler which decides which thread to run when.
If you need code to execute in a defined order on multiple threads, you need to add synchronization code between those threads.
Otherwise, the system is free to schedule execution in any order it sees fit.

Move to main thread after another thread go to sleep

I have my main and a thread running alongside it, I want to be able to run the thread first and then move to any other thread, for example, my main.
I tried to look over google but could not find an answer.
public class AutoUpdater implements Runnable {
public void run() {
System.out.println("Thread is running...");
for (int i = 0; i < clients.size(); i++) {
do something...
}
System.out.println("Thread ended.\n");
int time = 1000 * 60 * 60 * 24;
try {
Thread.sleep(time);
} catch (InterruptedException e) {
System.out.println("Something interrputed thread while running.");
}
}
public class Main {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Runnable runnable = new AutoUpdater(clients);
Thread thread = new Thread(runnable);
thread.start();
// run after the above thread finish and go to sleep
System.out.println("This is a test");
}
Like I said above I want my thread to finish and go sleep for X time, for example, 24 hours and when it goes to sleep move back to my main thread.
The goal is to make a bank system that updates all clients accounts first and then the method run (my second Thread) will go sleep for the next 24 hours. and move back my main.
What you have done in your code above created a thread that runs concurrently with the main thread. What actually happens is:
Main thread starts and initiates AutoUpdater thread
The two threads will run concurrently. In fact, the Main thread may even terminate before the AutoUpdater thread has really started.
The auto-update thread processes the clients ONCE, then sleeps for 24 hours and then terminates and your program completely terminates at this point.
So sticking with what you have, the first step is to get the AutoUpdater thread to run every 24 hours. One way you could do this is to keep the thread running and put a while loop in the run method so that it doesn't terminate but processes the clients collection every 24 hours. So now AutoUpdater might look like this:
public class AutoUpdater implements Runnable {
public void run() {
while (true) {
try {
System.out.println("Thread is running...");
for (int i = 0; i < clients.size(); i++) {
// do something...
}
} finally {
System.out.println("Thread ended.\n");
}
int time = 1000 * 60 * 60 * 24;
try {
Thread.sleep(time);
} catch (InterruptedException e) {
System.out.println("Something interrputed thread while running.");
}
}
}
}
However, the code above has some issues in that it will drift. If for example, processing takes an hour then the next time it runs will be 25 hours after the last run initial started. Fortunately, Java provides a thread executor service that will run your thread on a fixed schedule called ScheduledExecutorService. So let's unwind the while loop and introduce the executor instead.
public class AutoUpdater implements Runnable {
public void run() {
System.out.println("Thread is running...");
for (int i = 0; i < clients.size(); i++) {
// do something...
}
System.out.println("Thread ended.\n");
}
}
public static class Main {
public static void main(String[] args) throws IOException, ClassNotFoundException {
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
executor.scheduleAtFixedRate(
new AutoUpdater(clients, lock.writeLock()),
0,
24,
TimeUnit.HOURS);
System.out.println("This is a test");
}
}
Now we've got the auto-updater thread running every 24 hours from when we started the process. If you want to fix the time, i.e. at 8 AM every day you can either calculate the delay till that time (though this won't take into account daylight saving issues) or use a third-party library like Quartz to schedule at a specific time of day.
I want to be able to run the thread first and then move to any other thread, for example, my main.
Presumably by this, you mean that you want to stop other threads from executing while the Auto-Update is running. For this, you have several options available. In the first instance, you can use a monitor to synchronize and lock threads, i.e.
Object sharedMonitor = new byte[0]
// In your auto-updater and other threads
synchronised(sharedMonitor ) {
}
The syntax above will only allow a single thread to enter a synchronized block at a time for the same monitor instance. This would work fine in the example above where you only have the two threads. If you have more than the two threads it becomes problematic as you only really want the other threads to block when the auto-updater is running. In this case, this isn't the right solution for you. What you are after is something that will let all the threads run concurrently until the auto-updater needs to run and then they all need to block and wait for the auto-updater to finish. Fortunately for you, Java has a ReadWriteLock which does exactly that.
So let's add that lock and use it.
public static class Main {
private static List<String> clients = new ArrayList<>();
public static void main(String[] args) throws IOException, ClassNotFoundException {
ReadWriteLock lock = new ReentrantReadWriteLock();
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
executor.scheduleAtFixedRate(
new AutoUpdater(clients, lock.writeLock()),
0,
24,
TimeUnit.HOURS);
Lock readLock = lock.readLock();
while (true) {
try {
readLock.lock();
System.out.println("This is a test");
} finally {
readLock.unlock();
}
}
}
}
So above we have:
Added a read-write lock
Passed the write lock to AutoUpdater
Added a while loop to the main method so it doesn't terminate and can do whatever run-of-the-mill processing it is meant to be doing.
In the while loop we've acquired the read lock at the start and released it at the end.
The last piece of the puzzle is to use the write lock in AutoUpdater
public class AutoUpdater implements Runnable {
public void run() {
try {
lock.lock();
System.out.println("Thread is running...");
// do something...
}
} finally {
System.out.println("Thread ended.\n");
lock.unlock();
}
}
}

Running two tasks simultaneously in Java

I have two tasks that should be run together.
The first task to save the data to the database. And the second task of recording video.
Currently I use a Thread for each task, and run it simultaneously.
...
Thread insertDb = new Thread(new Runnable() {
#Override
public void run() {
// Insert to Database
setDataMediaVisit(thumbStr);
insertVisitRecord();
}
});
Thread capture = new Thread(new Runnable() {
#Override
public void run() {
if (getGraph().getState() == DSCapture.PREVIEW) {
getGraph().setCaptureFile("data/"+ CaptureController.getNoMr() +"/videos/"+videoStr, DSFilterInfo.filterInfoForProfile(new File("profiles/demo_profile800x570_WM8_VBR_100.prx")), DSFilterInfo.doNotRender(), true);
getGraph().record();
}
setData(CaptureController.getNoMr());
}
});
insertDb.start();
capture.start();
...
Is the above code thread safe?
I want to use EDT, but i know EDT for Java Swing Component. CMIIW
Thank you.
THread safe is just an issue, when do you want use object that are running in specific thread with another thread. It's not clear here that you are using the share object in this 2 thread or not! But, if you wanna use some share object or you want to read and write from file or specific butter, you can use lock object like this:
final Object lock = new Object();
// In thread 1
// TODO: do some process in thread on
synchronized(lock) {
// TODO: Put the result in somewhere that thread2 want to read it
}
// In thread 2
synchronized(lock) {
// TODO: get the result from the place that you put in thread 1
}
// TODO: do some process on thread 2 on the data
You should always remember that you need to put smallest possible synchronized, because if the other thread reach to synchronized part, it will wait until thread 1 finish synchronized block and it can kill the performance of your code

How can we save a thread for next task after its execution in java (Implementation of Thread pooling )

I need to ask about how thread pooling is implemented for having constant number of thread executing each time when there is task submission happened . (In Executor to avoid each time thread creation and deletion overhead)
executor.submit(Runnable)
Lets say we create some threads in the start and when task come we assign task to them(Thread) using any Queue impl . But after completing it s task how could a thread return to its pool again when as per the lifecycle of thread says that
"After execution of its run method it goes into TERMINATED state and can't be used again"
I am not understood how thread pool works for having constant number of threads for execution of any task to its queue .
It would be great if anyone could provide me an example of thread reuse after its completion of task .
!!Thanks in advance .!!
"After execution of its run method it goes into TERMINATED state and can't be used again"
It doesn't finish its run() Instead it has a loop which runs the run() of the tasks you provide it.
Simplifying the thread pool pattern dramatically you have code which looks like this.
final BlockingQueue<Runnable> tasks = new LinkedBlockingQueue<Runnable>();
public void submit(Runnable runs) {
tasks.add(runs);
}
volatile boolean running = true;
// running in each thread in the pool
class RunsRunnable implement Runnable {
public void run() {
while(running) {
Runnable runs = tasks.take();
try {
runs.run();
} catch(Throwable t) {
// handles t
}
}
}
}
In this example, you can see that while the run() of each task completes, the run() of the thread itself does not until the pool is shutdown.
Usually what happens when we use thread pool , Its inside Run method it is forced to run iteratively. Until there are tasks available in the Queue.
in the below example pool.removeFromQueue() will run iteratively.
public class MyThread<V> extends Thread {
private MyThreadPool<V> pool;
private boolean active = true;
public boolean isActive() {
return active;
}
public void setPool(MyThreadPool<V> p) {
pool = p;
}
/**
* Checks if there are any unfinished tasks left. if there are , then runs
* the task and call back with output on resultListner Waits if there are no
* tasks available to run If shutDown is called on MyThreadPool, all waiting
* threads will exit and all running threads will exit after finishing the
* task
*/
#Override
public void run() {
ResultListener<V> result = pool.getResultListener();
Callable<V> task;
while (true) {
task = pool.removeFromQueue();
if (task != null) {
try {
V output = task.call();
result.finish(output);
} catch (Exception e) {
result.error(e);
}
} else {
if (!isActive())
break;
else {
synchronized (pool.getWaitLock()) {
try {
pool.getWaitLock().wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
void shutdown() {
active = false;
}
Need to design your thread pool
public MyThreadPool(int size, ResultListener<V> myResultListener) {
tasks = new LinkedList<Callable<V>>();
threads = new LinkedList<MyThread<V>>();
shutDown = false;
resultListener = myResultListener;
for (int i = 0; i < size; i++) {
MyThread<V> myThread = new MyThread<V>();
myThread.setPool(this);
threads.add(myThread);
myThread.start();
}
}
You can take a look here: http://www.ibm.com/developerworks/library/j-jtp0730/index.html for more details and an implementation example. The threads in the pool will wait if the queue is empty and will each start consome messages once they are notified that the queue has some elements.
ExecutorService executor = Executors.newFixedThreadPool(2);
- The above statement created a ThreadPool with fixed size of 2.
executor.execute(new Worker());
- The above statement takes an instance of the class Worker which has implemented Runnable Interface.
- Now here the Executors is an intermediate object, executing the task. Which manages the Thread Objects.
- By executing the above statement the run() method will be executed, and once the run() method completes, the thread doesNot go into dead state but moves back into the pool, waiting to have another work assigned to it, so it can once again move into Runnable state and then to running, all this is handled by Executors .
executor.shutdown();
- The above statement will shutdown the Executors itself, gracefully handling the shutdown of all the threads managed by it..shutdown() on that central object, which in turn could terminate each of the registered executors.
////////// Edited Part//////////////////////
- First of all Runnable has a run() method which canNot return anything, and run() method canNot throw a checked exception, So Callable was introduced in Java 5, which is of Parametric type , and has a method called call(), and it is capable of returning , and throwing Checked exceptions.
Now see this Example:
Thread t = new Thread(new Worker());
t.run();
t.start();
- t.run() is just a simple call to run() method, this won't span a thread of execution.
- t.start() whereas prepares for the things important for the initialization of the thread of execution, and then calls the run() method of the Runnable, and then assign the Task to the newly formed thread of execution, and returns quickly....
Threads in Java becomes a necessity when using Swing and AWT. Mainly the GUI component.
I am totally agree with Peter but want add steps related to ExecutorService execution flow, for clear understanding.
If you create pool (fixed size pool) of threads it does not means that threads were created.
If you submit and/or execute new Task (Runnuble or Callable) new thread will be created JUTS if count of created threads < size of pool
Created threads not returning to pool, threads can wait for new value in blocking queue, this point we can call RETURNING TO POOL
All threads from pool execs like Peter described above.

Multiple threads. Doing similar tasks, but need to see their output

I have a program which I select the amount of threads and it starts it, but I would like to have control of closing each thread one by one after they have started and see there output of each thread as well.
What is the best approach in this case?
These methods allow you to fetch results of all tasks, that were submitted to an executor service. And this shuts it down.
Create a Hashtable that will contain your threads and have the thread name used as the Key in the hashmap. So whenever you want to perform an operation on your thread you can get its reference from the hashtable and do whatever you want with it.
Hashtable<String, Thread> threadTable = new Hashtable<String, Thread>();
Thread t1 = new Thread() {
public void run() {
//Do sttuff
}
}
Thread t2 = new Thread() {
public void run() {
//Do sttuff
}
}
threadTable.put("T1", t1);
threadTable.put("T2", t2);
Of course this the above is just a simple example. If you take a class and make it extends Thread, you can then add methods to suspend and resume the thread as well as printing out its status.

Categories

Resources