Home > Blockchain >  Multiple task but run concurrently in a separate thread
Multiple task but run concurrently in a separate thread

Time:11-06

I have encountered some challenge, I just want to confirm my knowledge is correct.

How are you going to implement this?

For example, if your program is written in Java the Sieve of Eratosthenes testing should run in one thread, and the Brute Force testing should run concurrently in a separate thread. Finally, your program should report the results of the benchmarking to the screen and exit.

Thank you Guys!

Is it Something like this?

class TestMultitasking4{  
 public static void main(String args[]){  
  Thread t1=new Thread(){  
    public void run(){  
      System.out.println("task one");  
    }  
  };  
  Thread t2=new Thread(){  
    public void run(){  
      System.out.println("task two");  
    }  
  };  
  
  
  t1.start();  
  t2.start();  
 }  
}  

CodePudding user response:

Your approach is correct although you might want to avoid creating anonymous classes by extending Thread inside the method.

The next step is to measure the elapsed time inside Runnable and use Thread.join() to wait for the threads to finish so you can display the results. Make sure to use the System.nanoTime() method and not currentTimeMillis() see here why.

If you feel like exploring Java standard library further take a look at things in the java.util.concurrent package e.g. a java.util.concurrent.ExecutorService.

CodePudding user response:

This is incorrect. If you run the program it will just start 2 threads and exit immediately because your main thread will not wait for the termination of t1 and t2.

You should:

  • Collect the results of your threads (you need callable and futures)
  • Wait for the threads to terminate (Thread.join is the primitive)

There are lots of ways to achieve this without using Threads directly using higher-level abstractions . The simplest way is probably using CompletableFuture

public static void main(String[] args) {
    CompletableFuture<Boolean> future1 = CompletableFuture.supplyAsync(() -> isPrime(42));
    CompletableFuture<String> future2 =  CompletableFuture.supplyAsync(() -> bruteForcePassword("encrypted"));

    var prime = future1.join();
    var pwd = future2.join();

    System.out.println("Was prime:"   prime);
    System.out.println("Password:"   pwd);
}

private static String bruteForcePassword(String s) {
    return "Alph@Rome0";
}

private static boolean isPrime(long value) {
    return false;
}
  • Related