I am trying to execute two method where two methods will execute one by one after some interval, and I am using ExecuterService. I have implemented some portion of the code but the full functionality I could not achieve till now, here I am posting my code
public class ExampleExecuterService {
private static final int MYTHREADS = 3000;
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newFixedThreadPool(MYTHREADS);
Object methodList[]={
aMethod(),bMethod()
};
for(int i=0;i<methodList.length;i++){
Object myList = methodList[i];
Runnable worker = new MyRunnable(myList);
executor.execute(worker);
}
executor.shutdown();
// Wait until all threads are finish
while (!executor.isTerminated()) {
}
System.out.println("\nFinished all threads");
}
public static class MyRunnable implements Runnable {
private Object myList=null;
MyRunnable(Object myList) {
this.myList = myList;
}
#Override
public void run() {
try{
myList.wait(2000);
}catch(Exception e){
e.printStackTrace();
}
}
}
private static Object bMethod() {
System.out.println("This is inside method a ");
return null;
}
private static Object aMethod() {
System.out.println("This is inside method b ");
return null;
}
}
I want aMethod() and bMethod() that should run 20 seconds after and in the end the executer will stop. How to do that with my code. Somebody please help me.
Object methodList[]={
aMethod(),bMethod()
};
This is not a list of your methods. This is a list of what your methods return (=null).
In Java, methods are not objects. If you want to store methods in a list or array, you have to wrap them inside objects. The usual way of doing this is by using the Runnable interface or something of the kind.
In your case, it could look like this:
Runnable[] methods = new Runnable[]{
new Runnable(){ // Object wrapper for method a
#Override
public void run(){ // method a
System.out.println("This is inside method a");
}
},
new Runnable(){ // Object wrapper for waiting
#Override
public void run(){ // method to wait for 20s
try{ Thread.sleep(20000); }catch(Exception e){}
}
},
new Runnable(){ // Object wrapper for method b
#Override
public void run(){ // method b
System.out.println("This is inside method b");
}
}
};
After that you can submit this array of "methods" to your executor service:
ExecutorService service = Executors.newSingleThreadExecutor();
for(Runnable r : methods)
service.submit(r);
service.shutdown();
However, keep in mind that ExecutorService is primarily meant to execute tasks concurrently (= in parallel), while you want to execute them sequentially.
In you know that you'll always need a sequential, single-thread behaviour, you should drop ExecutorService and simply:
for(Runnable r : methods)
r.run();
EDIT: Full main method
public static void main(String[] args) throws Exception {
Runnable[] methods = new Runnable[]{
new Runnable(){ // Object wrapper for method a
#Override
public void run(){ // method a
System.out.println("This is inside method a");
}
},
new Runnable(){ // Object wrapper for waiting
#Override
public void run(){ // method to wait for 20s
try{ Thread.sleep(20000); }catch(Exception e){}
}
},
new Runnable(){ // Object wrapper for method b
#Override
public void run(){ // method b
System.out.println("This is inside method b");
}
}
};
ExecutorService service = Executors.newSingleThreadExecutor();
for(Runnable r : methods)
service.submit(r);
service.shutdown();
// Wait until all threads are finish
while (!service.isTerminated()) {}
System.out.println("\nFinished all threads");
}
I didn't find a better solution for the waiting 20 seconds in between, but how about this:
ExecutorService service = Executors.newSingleThreadExecutor();
service.submit(task1);
service.submit(() -> {
Thread.sleep(20000);
return null;
});
service.submit(task2);
Related
I create a Callable which should make a syncExec call. I delegate the Callable to a subclass of RecursiveTask (ForkJoinPool) which executes the call method of the Callable. The problem is that the code inside the run method is never reached. Do you know why and how to fix that?
public class someClass{
public static void main (String[] args){
Callable<Object> c = new Callable<Object>() {
#Override
public Object call() throws Exception {
PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() {
#Override
public void run() {
System.out.println("hi");
}
});
return null;
}
});
ATLockTask task = new ATLockTask();
task.setCallable(c);
ForkJoinPool pool = new ForkJoinPool();
pool.invoke(task);
}
}
public class ATLockTask extends RecursiveTask<Object[]>{
Callable callable;
#Override
protected Object[] compute() {
try {
callable.call();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
ForkJoinPool.invoke blocks the current thread until the given task has completed. Display.syncExec waits until the SWT UI thread executes Display.readAndDispatch so it will wait forever because ForkJoinPool.invoke is blocking the UI thread.
Use ForkJoinPool.execute to start the task without blocking and the code works.
I've a core method in my project which I need it to be synchronized in order not to be accessed twice at the same time, and hence I have a thread which uses an instance from this class to access this method, but inside this thread I need to have a long life loop to be used to access the same method with a fixed value so I have to use another thread in order to allow the first thread to move on and complete it's duties, but for sure the method doesn't run from that second thread using the same instance used in the first thread, and somehow I can't instantiate another instance from the class as I have to use this instance exactly, so how to overcome this problem.
below is the problem translated to java:
public class ClassOne {
synchronized public void my_method(int number) {
// Do some Work
}
}
public class ClassTwo {
private void some_method() {
Thread one = new Thread(new Runnable() {
#Override
public void run() {
ClassOne class_one = new ClassOne();
// DO Work
class_one.my_method(0);
run_loop(class_one);
// Complete Work
}
});
one.start();
}
boolean running = true;
private void run_loop(final ClassOne class_one) {
Thread two = new Thread(new Runnable() {
#Override
public void run() {
while (running) {
class_one.my_method(1); // won't run
Thread.sleep(10000);
}
}
});
two.start();
}
}
Actual problem overview:
my_method --- > is to send UDP packets.
the method has to be synchronized otherwise I'll get the socket is already open exception when trying to use it more than once repeatedly.
at some point, I have to send a KeepAlive message repeatedly each 10 seconds, so, I have to launch a separate thread for that which is thread two in run_loop method.
Putting something that will compile and work. I don't see why you need this function to be synchronized. Check the output for this program...The second thread access this method only when the first thread is done accessing (unless you have missed adding some additional code).
class ClassOne {
int criticalData = 1;
synchronized public void my_method(int number) {
// Do some Work
criticalData *= 31;
System.out.println("Critical data:" + criticalData + "[" + Thread.currentThread().getName() + "]");
}
}
class ClassTwo {
boolean running = true;
public void some_method() {
Thread one = new Thread(new Runnable() {
public void run() {
ClassOne class_one = new ClassOne();
// DO Work
class_one.my_method(0);
run_loop(class_one);
// Complete Work
}
});
one.start();
}
public void run_loop(final ClassOne class_one) {
Thread two = new Thread(new Runnable() {
public void run() {
while (running) {
class_one.my_method(1); // won't run
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
two.start();
}
}
public class StackExchangeProblem {
public static void main(String[] args) {
ClassTwo two = new ClassTwo();
two.some_method();
}
}
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()) {}
}
}
}
In my app I start multiple media downloads in Threads via ThreadPoolExecutor. Now I want to be able to pause particular download threads. How I can do this?
well I'm not sure how you have implemented your code, so I'm just guessing here.
One way of doing this, by keeping track of your Threads,
for example create a Map :
Map<String,Thread> threads=new HashMap<String,Thread>();// ensure each Thread has a unique id, in this case its supposedly a String. then you can control them from outside your thread pool.
here is a hacked implementation:
public class hello{
public static void main(String...strings )throws Exception{
ExecutorService executor = Executors.newFixedThreadPool(5);
Map<String,Thread> threads=new HashMap<String, Thread>();
for(int i=0;i<5;i++){
Thread t = new myRunnable((i+1) +" ");
threads.put((i+1)+"", t);
executor.execute(t);
}
Thread.sleep(2000);
((myRunnable)threads.get("1")).isSuspened=true;
}
private static class myRunnable extends Thread{
String a;
public boolean isSuspened=false;
public myRunnable(String a) {
this.a=a;
// TODO Auto-generated constructor stub
}
#Override
public void run(){
while(true){
if(isSuspened){
continue;
}
try{
System.out.println(a);
Thread.sleep(2000);
}catch(Exception e){}
}
}
}
}
I have 2 classes. One method of the class calls the other class' method, but it has to wait until the method finishes to proceed to the execution of the rest of the code.
This is a rough code of what I'm trying to make. And I know this doesn't work.
public class Example
{
Thread thread;
public Example(Thread thread)
{
this.thread = thread;
}
public void doSomethingElse()
{
System.out.println("Do something else");
thread.notify();
}
}
public class Example2
{
Thread thread;
Example example;
public Example2()
{
example = new Example(thread);
thread = new Thread()
{
public void run()
{
example.doSomethingElse();
try {
this.wait();
} catch (InterruptedException ex) {
}
System.out.println("Do something");
}
};
}
public void doSomething()
{
thread.run();
}
}
Now do you know how to make this right?
Not sure if your constrained to using this particular approach (wait/notify) however a better approach is taking advantage of the Java Concurrency API
public class ExampleCountDownLatch
{
public void doSomething () throws InterruptedException
{
final CountDownLatch latch = new CountDownLatch(1);
Thread thread = new Thread()
{
public void run ()
{
System.out.println("do something");
latch.countDown();
}
};
System.out.println("waiting for execution of method in your example class");
thread.start();
// wait for reasonable time otherwise kill off the process cause it took
// too long.
latch.await(3000, TimeUnit.MILLISECONDS);
// now I can do something from your example 2
System.out.println("now i can execute from example 2 do something else");
}
}
Anyway just another approach if you had an option.
UPDATE:
Here is a blog about this very topic.
Couple of points :
you should acquire lock before calling wait or notify method. The
lock must be on same object. In code you are calling wait on example2
object but calling notify on different object.
thread.run() means calling run method of thread object, its not
creating new thread its same as example.doSomething(). When you
create thread start that thread by calling start method.
Here is my implementation
class Example implements Runnable
{
public void run()
{
doSomething();
}
public void doSomething(){
synchronized(this){
System.out.println("Do something else");
try{
Thread.sleep(1000);
this.notify();
}catch (InterruptedException ignore) {}
}
}
}
class Example2 implements Runnable
{
Thread thread;
Example example;
public Example2(Example example){
this.example = example;
}
public void run(){
doSomething();
}
public void doSomething(){
synchronized(example){
System.out.println("waiting for example 1 to complete");
try{
example.wait();
}catch (InterruptedException ignore) {}
}
System.out.println("Do something");
}
}
public class Entry{
public static void main(String[] args){
Example example = new Example();
Example2 obj = new Example2(example);
Thread t = new Thread(obj);
t.start();
Thread t2 = new Thread(example);
t2.start();
}
}
In code Thread.sleep(1000); statement is not needed.
Here is one more implementation using join method
class Example implements Runnable
{
public void run()
{
doSomething();
}
public void doSomething(){
System.out.println("Do something else");
try{
Thread.sleep(1000);
}catch (InterruptedException ignore) {}
}
}
class Example2 implements Runnable
{
Thread thread;
Example example;
public Example2(Example example){
this.example = example;
}
public void run(){
System.out.println("waiting for example 1 to complete");
Thread t = new Thread(example);
try{
t.start();
t.join();
}catch(InterruptedException ie){
}
doSomething();
}
public void doSomething(){
System.out.println("Do something");
}
}
public class Entry{
public static void main(String[] args){
Example example = new Example();
Example2 obj = new Example2(example);
Thread t = new Thread(obj);
t.start();
}
}