Running two tasks simultaneously in Java - 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

Related

Java Threading: Is using interrupt() within run() acceptable to stop a thread when it is finished completing its task?

I have setup a Java Thread class which preforms a particular task of creating a new Process and running it along with various other things.
In the parent class which invokes the Thread I have setup a loop
while(!thread.isActive()) {
...
}
I wanted to know if it is best practices / acceptable to update the run() in the Thread class to issue a interrupt()
run() {
callTask();
interrupt();
}
Update
I could then create a boolean finished field on the Thread and change that to true once the callTask() is completed and have the parent look for
Thread:
run() {
callTask();
finished = true;
}
Parent:
// Start the threads for each Device
for (DeviceRunner deviceRunner : deviceRunners) {
deviceRunner.start();
}
boolean doneProcessingDevices = false;
while (!doneProcessingDevices) {
Set<DeviceRunner> deviceRunnersToRemove = new HashSet<DeviceRunner>();
for (DeviceRunner deviceRunner : deviceRunners) {
if (deviceRunner.isFinishedRunning()) { // check to see if the thread is finished
deviceRunnersToRemove.add(deviceRunner);
}
}
// remove the device runners which are no longer active
deviceRunners.removeAll(deviceRunnersToRemove);
if (deviceRunners.isEmpty()) {
doneProcessingDevices = true;
}
Thread.sleep(1000);
}
Thank you
Just to clarify: you don't have to stop threads manually. When run() completes, the native thread will die and the Thread object will be garbage collected.
If you want your parent to wait until all tasks completed, you can use a CountDownLatch. Initialize the latch with the number of tasks that have to be done. Every time a task finishes, let him invoke countDown(). In the meantime, your parent blocks on await():
Causes the current thread to wait until the latch has counted down to zero, unless the thread is interrupted.
This MWE demonstrates the basic idea:
int numberOfTasks = 3;
CountDownLatch latch = new CountDownLatch(numberOfTasks);
while (numberOfTasks-- > 0) {
new Thread(() -> {
try {
// Do stuff.
System.out.println("Done.");
} finally {
latch.countDown();
}
}).start();
}
try {
latch.await();
System.out.println("All tasks finished.");
} catch (InterruptedException e) { /* NOP */ }
You won't see All tasks finished. before each task has printed Done..
I believe what you are really looking for is Thread.join method. Copying from Oracle tutorial
The join method allows one thread to wait for the completion of another. If t is a Thread object whose thread is currently executing, t.join()
causes the current thread to pause execution until t's thread terminates

How to run certain parts of a program on a different Thread and reference variables to Thread?

So instead of "sleeping" a thread, as in Thread.sleep(); to merely allow the processes to run on another thread and make the new thread sleep with Thread.sleep(); but not the original Thread. Is this possible?
Here is my method that I want to run on a new Thread called processesThread:
private void Processes() throws IOException, InterruptedException {
// New Thread "processesThread" will start here.
Runtime rt = Runtime.getRuntime();
List<Process> processes = new ArrayList<Process>();
// "runnableTogether" will be the number that the user inputs in the GUI.
switch (runnableTogether) {
case 4:
processes.add(rt.exec("C:/Windows/System32/SoundRecorder.exe"));
case 3:
processes.add(rt.exec("C:/Windows/System32/taskmgr.exe"));
case 2:
processes.add(rt.exec("C:/Windows/System32/notepad.exe"));
case 1:
processes.add(rt.exec("C:/Windows/System32/calc.exe"));
Thread.sleep(5000);
destroyProcesses(processes);
break;
default:
System.exit(0);
break;
}
// New Thread "processesThread" will end here.
}
Is this possible? And if so, how?
I have researched starting new Threads, but I can't quite figure out how to get it to work with my program.
EDIT: I was hoping to use something similar to this approach:
Thread processesThread = new Thread() {
public void run() {
// Code here.
}
};
processesThread.start();
Any ideas?
If I get your question right, you want to know how to sleep other threads while the current thread remains in running state. You can use wait and notify.
Here is an example;
final Object mon = ...;
Thread t1 = new Thread(new Runnable() {
#Override
public void run() {
synchronized (mon) {
try {
mon.wait(); //blocks the t1 thread
} catch (InterruptedException e) {
//
}
}
}
});
mon.wait() blocks the t1 thread until another thread invokes mon.notify() to wake the thread that is waiting on the mon object. You can also call mon.notifyAll() if more than one thread is waiting on the monitor - this will wake all of them up. However, only one of the threads will be able to grab the monitor (remember that the wait is in a synchronized block) and carry on - the others will then be blocked until they can acquire the monitor's lock.

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.

How to check if an Android Thread is running

Is there a way to check if a Thread object has had start called on it already?
I'm trying to so something like:
if(rt.isAlive() == true)
{
Log.v(TAG, "START RECORD");
rt.recording = true;
}
else
{
Log.v(TAG, "START THREAD/RECORD");
rt.start();
}
where it would start the thread if it's not already running.
Assuming that rt is a Thread, just check rt.isAlive().
Alternatively, just use a boolean flag and set it to true right before you start your thread.
I would actually prefer the boolean approach so there is no way that the main thread could start the other thread twice - there may be a short delay until your Thread is up and running, and if your main thread tries to start the thread twice in quick succession, it may get a "false" negative on rt.isAlive().
I've used this approach with success:
if ( mythread.getState() == Thead.State.NEW )
//then we have a brand new thread not started yet, lets start it
mythread.start();
else
//it is running already compensate
If you called start on it, and it is running, you will get an IllegalThreadStateException. Catching that is one way to know.
Another option is to extend Thread and add a boolean where you keep track of whether or not your Thread has been started. You can override the start method of Thread to check the boolean before calling up to super.start().
You should be very careful when using threads in Android though. Make sure you understand the lifecycle of the component that is starting it. Also, you should consider some of the helper classes like Handler and AsyncTask instead of directly spawning threads.
Call this method by passing a thread. It will check the thread is alive or not, every 500 milliseconds with start delay of 500 milliseconds (you can use your custom values). I use this method often.
void threadAliveChecker(final Thread thread) {
final Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
if (!thread.isAlive()) {
// do your work after thread finish
runOnUiThread(new Runnable() {
#Override
public void run() {
// do the ui work here
}
});
timer.cancel();
}else {
// do work when thread is running like show progress bar
}
}
}, 500, 500); // first is delay, second is period
}
Example:
Thread thread = new Thread(myRunnable);
thread.start();
threadIsAliveChecker(thread);
This method will let us know when the thread is finished doing its work.

Categories

Resources