I have 2 jobs I want to execute in JAVA. I have:
public static void main(String[] args)
{
takeInfofromDB();
doSomeLongCalculationsWithThatData();
takeInfofromDB2();
doSomeLongCalculationsWithThatData2();
GenerateAnswerFromBothAnswers();
}
Is it possible to somehow put takeInfofromDB(); and doSomeLongCalculationsWithThatData(); in 2 Threads? And GenerateAnswerFromBothAnswers(); can't execute while at least one is still working?
Like this...
public static void main(String[] args)
{
Thread t1 = new Thread(new Runnable() {
public void run() {
takeInfofromDB();
doSomeLongCalculationsWithThatData();
}});
Thread t2 = new Thread(new Runnable() {
public void run() {
takeInfofromDB2();
doSomeLongCalculationsWithThatData2();
}});
t1.start();
t2.start();
t1.join();
t2.join();
GenerateAnswerFromBothAnswers();
}
For a very simple lightweight approach, try the following code. However you may want to read more about Threads and eventually Executors: http://docs.oracle.com/javase/tutorial/essential/concurrency/
Thread thread1 = new Thread() {
private Object result;
#Override
public void run() {
takeInfofromDB();
result = doSomeLongCalculationsWithThatData();
}
public Object getResult() {
return result;
}
}
Thread thread2 = new Thread() {
private Object result;
#Override
public void run() {
takeInfofromDB2();
result = doSomeLongCalculationsWithThatData2();
}
public Object getResult() {
return result;
}
}
thread1.start();
thread2.start();
thread1.join();
thread2.join();
Object result1 = thread1.getResult();
Object result2 = thread2.getResult();
GenerateAnswerFromBothAnswers(result1, result2);
You shouldn't run this code as is (I haven't tested it, and weird things could happen if you call getResult before join), but it should serve as a starting point for how to use threads in a basic way.
Related
I have a method called processOutbox. I want it to be thread safe. I don't want another thread to call this method while one thread is at it. I have implemented it the following way. Have I done it correctly? Are there any loopholes in my implementation? If there are any, then please advice on how I can resolve it.
this.start();
outboxLock.lock();
timer = new Timer();
try{
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
processOutbox();
}
}, 0, period);
} finally{
outboxLock.unlock();
}
If you want to make your method processOutbox, you should use the keyword synchronized:
public class YourClass{
public synchronized void processOutbox(){
//do all you want
}
}
More info at:https://docs.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html
If in your code you have an instance of YourClass called for example myInstance , all calls to processOutbox() will be thread safe because they will be locked at instance level.
For example:
YourClass myInstance = new YourClass();
Thread thread1 = new Thread(){
public void run(){
myInstance.processOutbox();
}
}
Thread thread2 = new Thread(){
public void run(){
myInstance.processOutbox();
}
}
thread1.start();
thread2.start();
Here thead2 will be waiting until thread1 finishes the call to "processOutbox"
But for example:
YourClass myInstance = new YourClass();
YourClass myInstance2= new YourClass();
Thread thread1 = new Thread(){
#Override
public void run(){
myInstance.processOutbox();
}
};
Thread thread2 = new Thread(){
#Override
public void run(){
myInstance2.processOutbox();
}
}
thread1.start();
thread2.start();
thead2 will NOT wait because they are calling the method on different instances.
Someone specifically asked about using ReentrantLock -- So I'm adding that response on to this one, because this one is correct.
public class YourClass {
private Lock outboxLock = new ReentrantLock();
public void processOutbox() {
outboxLock.lock()
try {
// do stuff
} finally {
outboxLock.unlock()
}
}
}
I mention this specifically because you can also do things, where you keep other threads out of the lock without causing them to block by using tryLock instead.
public class YourClass {
private Lock outboxLock = new ReentrantLock();
public void processOutbox() {
if( outboxLock.tryLock() ) {
try {
// do stuff
} finally {
outboxLock.unlock()
}
}
}
}
Use a CountDownLatch for synchronization.
Im new to Threads and I was wondering how could I define what two or more different Threads do in a Java program. Do i define them all in the same public void run method? If so, how do I do it? I would like the Threat t1 to invoke the increment method, t2 to invoke the decrement method and both of them to call the value method
Here's the code example:
package interference;
/**
*
* #author rodrigopeniche
*/
public class Interference implements Runnable{
/**
* #param args the command line arguments
*
*/
Counter counter1= new Counter();
class Counter{
private int c= 0;
public void increment()
{
c++;
}
public void decrement()
{
c--;
}
public int value()
{
return c;
}
}
public static void main(String[] args) {
// TODO code application logic here
Thread t1= new Thread(new Interference());
Thread t2= new Thread(new Interference());
t1.start();
t2.start();
}
#Override
public void run() {
counter1.increment();
counter1.decrement();
counter1.value();
}
}
You can set names to threads like thread1, thread2. After that, in the run method, check the name of the thread currently running and do the necessary action.
You have to add a while loop inside the run method if you need to run it longer.
public static void main(String[] args) {
Interference interference = new Interference();//create a new Interference object
Thread t1 = new Thread(interference, "thread1");//pass the runnable interference object and set the thread name
Thread t2 = new Thread(interference, "thread2");//pass the runnable interference object and set the thread name
t1.start();
t2.start();
}
#Override
public void run() {
while (true) {//to run it forever to make the difference more visual
String threadName = Thread.currentThread().getName();//get the current thread's name
if (threadName.equals("thread1")) {//if current thread is thread1, increment
counter1.increment();
} else if (threadName.equals("thread2")) {//if current thread is thread2, decrement
counter1.decrement();
}
System.out.println(counter1.value());//print the value
}
}
When you run the code, you can see count is going up and down in a random manner.
In your current code, counter1 is an instance variable of class Interference. You create 2 instances of Interference and then use them to create two Thread objects. When the threads start to run, each Thread is actually working on it's own copy of counter1. I think that may not be what you expect.
package interference;
public class Interference {
static class Counter {
private int c = 0;
public void increment() {
c++;
}
public void decrement() {
c--;
}
public int value() {
return c;
}
}
public static void main(String[] args) {
Counter counter = new Counter();
Thread t1 = new Thread(new Runnable() {
public void run() {
counter.increment();
System.out.println(counter.value());
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
counter.decrement();
System.out.println(counter.value());
}
});
t1.start();
t2.start();
}
}
Suppose I have a method called Magic() I want to execute this method with three different thread.
I know how to execute Magic() method with a single thread, but I am confuse, How do I do with three different threads?
Suppose I have a method called Magic() I want to execute this method with three different thread
Create a MagicTask class that represents the task that each Thread will execute and call the magic() method inside run() :
class MagicTask implements Runnable {
public void run() {
magic();
}
public void magic() { //do magic }
}
Then create three threads and pass it the task :
Thread t1 = new Thread(new MagicTask());
Thread t2 = new Thread(new MagicTask());
Thread t3 = new Thread(new MagicTask());
Then start the threads :
t1.start();
t2.start();
t3.start();
Note You can pass the same MagicTask instance to all three Thread instances as well. Remember that if MagicTask has state that can get inconsistent when accessed by different threads, you also need to make your class thread-safe by using intrinsic locking using synchronized or other such constructs which are out of the scope for this answer.
class Multi3 implements Runnable{
public void run(){
System.out.println("thread is running...");
call();
}
void call(){
System.out.println("method call by"+Thread.currentThread().getName());
}
public static void main(String args[]){
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
Thread t2 =new Thread(m1);
Thread t3 =new Thread(m1);
t1.start();
t2.start();
t3.start();
}
}
Here Thread t1,t2,t3 are calling the same method call().
If you are using Java 8, function references are straightforward:
public class Main {
public static void magic() {
System.out.println("this is magic");
}
public static void main(final String args[]) {
new Thread(Main::magic).start();
new Thread(Main::magic).start();
new Thread(Main::magic).start();
}
}
And if magic isn't a static method use:
public class Main {
public void magic() {
System.out.println("this is magic");
}
public static void main(final String args[]) {
Main m = new Main();
new Thread(m::magic).start();
new Thread(m::magic).start();
new Thread(m::magic).start();
}
}
You can try Like.
I am dividing the task to different thread
Try your own logic it just a simple even count,
public class CountNumber implements Runnable {
int stop;
int start;
int totalEvenNo;
public CountNumber(int start, int stop)
{
this.start=start;
this.stop=stop;
}
public void run()
{
int total= countEven(start, stop);
System.out.println("Total Even numbers are :"+total);
}
public int countEven(int str,int stp)
{
for(int i=str;i<=stp;i++)
{
if(i%2==0)
{
totalEvenNo +=1;
System.out.println(totalEvenNo);
}
}
return totalEvenNo;
}
}
public class MainClassNumber {
public static void main(String[] args) {
System.out.println("Spawaning Thread.........");
Thread t1 = new Thread(new CountNumber(0, 500000));
Thread t2 = new Thread(new CountNumber(500001, 2000000));
Thread t3 = new Thread(new CountNumber(2000001, 5000000));
Thread t4 = new Thread(new CountNumber(5000001, 10000000));
Thread t5 = new Thread(new CountNumber(10000001, 20000000));
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
}
}
Call it directly like magic(); And for better result synchronize that method like below
public synchronized void magic(){
//your code
}
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class WorkerThread implements Runnable {
public void run() {
Magic();
}
private void Magic() {
// consider synchronizing this method, but if you do method will be accessable by one thread at a time.
}
}
public class TestThreadPool {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(3)
for (int i = 0; i < 3; i++) {
Runnable worker = new WorkerThread();
executor.execute(worker);
}
executor.shutdown();
while (!executor.isTerminated()) {}
}
}
}
So, i apologize for the title. It's quite hard to explain in one sentence what i would like to do if you have no idea on how it is called.
So assume i can only use primitive thread functions (wait, notify, no concurrent package)
The program has 3 threads, all of them are the same and are called by the main thread. They behave normally until one of the three get an exception and so it must wait for the end of the remaining 2 threads in order to start a recovery process.
I was thinking about a static variable but I'm not really sure about it, i would love to keep it as simple as possible.
Each thread starts at the same time.
I don't see any reason why you can't use a static variable like you suggest. Here's how I would do it with an inner class...
private static boolean running = true;
public void test26546397() {
while (true) {
Thread t1 = new Thread(new MyRunnable());
Thread t2 = new Thread(new MyRunnable());
Thread t3 = new Thread(new MyRunnable());
t1.start();
t2.start();
t3.start();
try {
t1.join();
t2.join();
t3.join();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
running = true;
// Do recovery
}
}
public class MyRunnable implements Runnable {
#Override
public void run() {
while (running) {
try {
// doStuff
} catch (Exception ex) {
running = false;
}
}
}
}
I would of course replace the while (true) with something a little more suitable.
I think you need java.concurrent.CountdownLatch, however if the java.concurrent package is not available to you can code this yourself using Object.wait/notify and synchronized blocks.
The latch can then be decremented in a finally {} on each Thread, this will be run if the Thread completes, or an exception occurs.
Your main program then just needs to wait for count to become 0.
public class StackOverflow26546397 {
static class CountdownLatch {
private int count;
private Object monitor = new Object();
public CountdownLatch(int count) {
this.count = count;
}
public void countDown() {
synchronized (monitor) {
count--;
monitor.notifyAll();
}
}
public void await() throws InterruptedException {
synchronized (monitor) {
while (count > 0) {
monitor.wait();
}
}
}
}
static class Job implements Runnable {
private CountdownLatch latch;
public Job(CountdownLatch latch) {
this.latch = latch;
}
#Override
public void run() {
try {
// do work.
Thread.sleep((long) (Math.random() * 3000d));
} catch (InterruptedException e) {
//
} finally {
latch.countDown();
}
}
}
public static void main(String[] args) throws InterruptedException {
CountdownLatch latch = new CountdownLatch(3);
new Thread(new Job(latch)).start();
new Thread(new Job(latch)).start();
new Thread(new Job(latch)).start();
latch.await();
System.out.println("All threads finished");
}
}
Not sure what you are trying to do but this is as simple as I can think of (just native concurrency):
Create a static or shared volatile boolean
private static volatile boolean exceptionOccured=false
Set the above to 'true' when exception occurs:
....}catch(Exception e){
exceptionOccured=true;
}
Check this periodically in you normal thread flow:
if (exceptionOccured)
//enter you synchronized call here
the synchronized method could look something like:
public synchronized void checkAndRecover(){
//decrement a counter or other logic to identify which is the last Thread and then
//perform any recovery logic
}
I have a class with name Socket that have tow function for example func1 and func2
fucn1() {
while(true) {
...
}
}
fucn2() {
while(true) {
...
}
}
I want two of them run with thread in a time and concurrently. how can i do that??
class socket implement Runnable {
public void run() {
func1();
func2();
}
}
In this code only first function is executed not second. How can i do for concurrently run both of them?
My Suggestion is :
Instead of making socket Class Runnable,
Create two Runnable threads as in my example below and call your functions from there. And start these two threads from your Socket class.
class Socket{
private void startThreads() {
new Thread(new Th1()).start();
new Thread(new Th2()).start();
}
}
class Th1 implements Runnable {
#Override
public void run() {
fucn1();
}
}
class Th2 implements Runnable {
#Override
public void run() {
fucn2();
}
}
You can run them concurrently like this:
// start a thread for func1
Thread t1 = new Thread(new Runnable() {
public void run() {
func1();
}
});
t1.start();
// func2 will run in parallel on the main thread
func2();
t1.join(); // if you want to wait for func1 to finish.
You haven't given any details, so I'm assuming they have no side-effects.
If you want to run the two functions concurrently, spawn two threads and run each function in its own thread.
That's precisely what threads are for.
You need to create two threads for this scenario.
class socket implement runable
{
boolean condition;
public socket(boolean condition){
this.condition = condition;
}
public void run()
{
if(condition == true){
func1();
}else{
func2();
}
}
}
Thread t1 = new Thread(new Socket(true));
Thread t1 = new Thread(new Socket(false));
t1.start();
t2.start();
In addition to this you need to yield control in each method just to make sure that every thread will get fair chance to run.