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

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.

Related

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

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.

Main thread to wait two parallel threads children java

first what i am trying to do:
During the main thread execution i want to pause the main thread and start two parallel threads. As soon as both this parallel threads terminate, i'd like to start again with the main thread.
What i tried:
...
...
main thread is executing
...
...
CyclicBarrier barrier = new CyclicBarrier(2);
Thread child1 = new Thread(new ThreadBuilderTask(barrier,0));
Thread child2 = new Thread(new ThreadBuilderTask(barrier,1));
child1.start();
child2.start();
/* Now i'm expecting that child1 and child2 are running in parallel calling their fooFunction */
child1.join();
child2.join();
/*Now i'm expecting that main thread will wait for child1and also for child2 (that are running in parallel).*/
... main thread starts again after both child1 and child2 finished (reached the await of the barrier)
... (break point set here, never reached)
...
Thread builder custom class
public class ThreadBuilderTask implements Runnable{
private CyclicBarrier barrier;
private int index;
...setters and getters..
#Override
public void run() {
fooFunction(this.getIndex());
try {
this.getBarrier().await();
} catch (InterruptedException | BrokenBarrierException e) {
return;
}
}
public ThreadBuilderTask(CyclicBarrier barrier,int index){
this.barrier = barrier;
this.index = index;
}
public fooFunction(int index){
//Something taking some seconds to execute
}
It's not clear what is happening here but it is definetely not working. As soon as i call join everything stops and the main thread never restart. (I put a breakpoint after the joins to see when the main thread restarts).
Maybe there is a bit of confusion with these concepts and also i'm not sure if i need to use both the barrier and the joins or simply one of those techniques.
Thanks
Davide
As mentioned in the comments I'd also suggest to use CompletableFuture. A very basic example of your described requirements could look like this:
final Runnable runnable1 = ...;
final Runnable runnable2 = ...;
CompletableFuture<Void> future1 = CompletableFuture.runAsync(runnable1);
CompletableFuture<Void> future2 = CompletableFuture.runAsync(runnable2);
CompletableFuture.allOf(future1, future2).get(); // waits for both runnables to finish
You might want to add more/some exception handling to this example. But it should give an idea how this might work.
You may consider to use Java CompletableFuture to achieve the objective.
Using its functions like supplyAsync or runAsync you may start child threads and join their respective result in the end. Or you can simply let the main thread wait until the subsequent threads completes.
Recently I managed to implement a sample scatter-gather function using the same class.
Check Java Doc for more offerings and to find best available function: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html

Can this reference in run() refer to Thread object when implementing Runnable?

Sorry if the question is unclear
I am making a simple multithread program that has a linked list to store all thread created except the main thread. Then I want to send some signal to terminate the main thread but only when all other threads have closed and I intend to do this by making that when the thread close, it will remove itself from linked list then the main thread will check if that list size == null or not
here is my code
public class MainProgram {
//some global static variable
static List<Thread> threadList = new LinkedList<Thread>();
public void main() throws IOException {
ServerSocket serverSocket;
serverSocket = new ServerSocket(1234);
while(true){
if(Shutdown_Handler.shutdown==true){
//wait for all other thread close/terminate
return
}
Socket s = serverSocket.accept();
ClientThread x = new ClientThread(s);
Thread y = new Thread(x);
threadList.add(y);
y.start();
}
}
}
when Shutdown_Handler.shutdown==true the main will check the threadList if it is null. The problem is I don't know how to make the thread remove itself from the list. As what I have searched, for normal object, I can create method like this
public class someObject {
public static void delete(){
if(list.size = null) return;
list.remove(this);
}
}
However, in case of thread, the Class implement Runnable so this reference is to the object but not the thread stored in the list
I would recommend using a HashMap instead of a List. The keys can be the Thread Name (e.g. Thread.getName()) and the values will be the Threads.
Map<String, Thread> threadMap = new HashMap<String, Thread>();
You should also create this Map as a synchronizedMap (using Collections.synchronizedMap(...))
Map<String, Thread> synchronizedMap = Collections.synchronizedMap(threadMap);
Now, whenever you construct a Thread, you pass this HashMap into its constructor and the Thread can hold a reference to it. Therefore, when the Thread is about to terminate it can remove itself from the HashMap by using its own Thread name as the key to remove.
Assuming that ClientThread is a Runnable, the basic code is:
public class ClientThread implements Runnable {
public void run() {
// do stuff
MainProgram.threadList.remove(Thread.currentThread());
}
}
However this has a couple of problems:
There are going to be multiple threads performing operations on a list without proper synchronization. That is incorrect, and you are liable to get intermittent failures if you do this.
Unless run() removes the thread from the list in a finally block, a thread that terminates abnormally is liable to not get removed.
It is bad design to use a global static. And worse design to expose it as a bare (non-private) variable.
A HashSet<Thread> would be more efficient if the number of threads is liable to be large.

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

Java - Basic Multithreading

I would like to ask basic question about Java threads. Let's consider a producer - consumer scenario. Say there is one producer, and n consumer. Consumer arrive at random time, and once they are served they go away, meaning each consumer runs on its own thread. Should I still use run forever condition for consumer ?
public class Consumer extends Thread {
public void run() {
while (true) {
}
}
}
Won't this keep thread running forever ?
I wouldn't extend Thread, instead I would implement Runnable.
If you want the thread to run forever, I would have it loop forever.
A common alternative is to use
while(!Thread.currentThread().isInterrupted()) {
or
while(!Thread.interrupted()) {
It will, so you might want to do something like
while(beingServed)
{
//check if the customer is done being served (set beingServed to false)
}
This way you'll escaped the loop when it's meant to die.
Why not use a boolean that represents the presence of the Consumer?
public class Consumer extends Thread {
private volatile boolean present;
public Consumer() {
present = true;
}
public void run() {
while (present) {
// Do Stuff
}
}
public void consumerLeft() {
present = false;
}
}
First, you can create for each consumer and after the consumer will finish it's job than the consumer will finish the run function and will die, so no need for infinite loop. however, creating thread for each consumer is not good idea since creation of thread is quite expensive in performance point of view. threads are very expensive resources. In addition, i agree with the answers above that it is better to implement runnable and not to extends thread. extend thread only when you wish to customize your thread.
I strongly suggest you will use thread pool and the consumer will be the runnable object that ran by the thread in the thread pool.
the code should look like this:
public class ConsumerMgr{
int poolSize = 2;
int maxPoolSize = 2;
long keepAliveTime = 10;
ThreadPoolExecutor threadPool = null;
final ArrayBlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(
5);
public ConsumerMgr()
{
threadPool = new ThreadPoolExecutor(poolSize, maxPoolSize,
keepAliveTime, TimeUnit.SECONDS, queue);
}
public void runTask(Runnable task)
{
// System.out.println("Task count.."+threadPool.getTaskCount() );
// System.out.println("Queue Size before assigning the
// task.."+queue.size() );
threadPool.execute(task);
// System.out.println("Queue Size after assigning the
// task.."+queue.size() );
// System.out.println("Pool Size after assigning the
// task.."+threadPool.getActiveCount() );
// System.out.println("Task count.."+threadPool.getTaskCount() );
System.out.println("Task count.." + queue.size());
}
It is not a good idea to extend Thread (unless you are coding a new kind of thread - ie never).
The best approach is to pass a Runnable to the Thread's constructor, like this:
public class Consumer implements Runnable {
public void run() {
while (true) {
// Do something
}
}
}
new Thread(new Consumer()).start();
In general, while(true) is OK, but you have to handle being interrupted, either by normal wake or by spurious wakeup. There are many examples out there on the web.
I recommend reading Java Concurrency in Practice.
for producer-consumer pattern you better use wait() and notify(). See this tutorial. This is far more efficient than using while(true) loop.
If you want your thread to processes messages until you kill them (or they are killed in some way) inside while (true) there would be some synchronized call to your producer thread (or SynchronizedQueue, or queuing system) which would block until a message becomes available. Once a message is consumed, the loop restarts and waits again.
If you want to manually instantiate a bunch of thread which pull a message from a producer just once then die, don't use while (true).

Categories

Resources