It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I want to print an array only after 2 threads that I created are finish run method.
How can iI do that?
Take a look at the method Thread#join(). For example:
Thread a = ...;
a.start();
a.join(); // wait until Thread a finishes
Simple. Use Thread.join(). While you are spawning your threads add them into a list and loop through that list and call thread.join(). Once you get out of that loop, all your threads are confirmed to be finished. Then you can have the print statement after that.
Something like this:
import java.lang.*;
public class ThreadDemo implements Runnable {
public void run() {
//some implementation here
}
public static void main(String args[]) throws Exception {
List<Thread> threadList = new ArrayList<Thread>();
Thread t1 = new Thread(new ThreadDemo());
t1.start();
threadList.add(t1);
Thread t2 = new Thread(new ThreadDemo());
t2.start();
threadList.add(t2);
for(Thread t : threadList) {
// waits for this thread to die
t.join();
}
System.out.print("All the threads are completed by now");
}
}
Have you tried anything?
The standard way of having code wait for a thread to finish is to call the join() method on that thread; when that returns, the thread is done. Try looking that up and seeing what you can figure out.
Take a look to this post (How to wait for a set of threads to complete?, How to wait for a number of threads to complete?).
You could submit these jobs to an Executor, each of them will return a Future object. Call the get() method on each of these futures and you'll block until all of them have completed:
String[] myArr = new String[0];
ExecutorService service = Executors.newSingleThreadExecutor();
//Just one task, but repeat with as many as needed.
Future f = service.submit(new Runnable() {
public void run() {
//Executing code
}
});
f.get();
System.out.println(Arrays.toString(myArr)); //Print array.
Thread.join() is the more standard way to wait until a particular thread has completed, but personally in this day and age I prefer this approach - it makes it much easier to say swap out the single threaded executor for a concurrent thread pool (or similar) later should the need arise, and personally I find it neater too. It can also be easily refactored to work with Callables, providing a Future which can directly get the result of the concurrent computation.
Either approach will work, the one which is better for you will depend on your use case.
My opinion is that you should use CountDownLatch.
Before printing you should show this:
CountDownLatch startSignal = new CountDownLatch(2);
// Create your threads and add startSignal as parameters to them
At the end of each thread you shoulf call:
startSignal.countDown();
After that before print you should call:
startSignal.await();
// print...
This will continue after counter reaches zero.
Related
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.
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();
}
}
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.
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;
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
From another post:
If a Thread needs to be run more than once, then one should make an
new instance of the Thread and call start on it.
How is this done?
I would use another layer of abstraction. Use an ExecutorService.
Here is a simple example:
public static void main(String args[]) throws InterruptedException {
final ExecutorService service = Executors.newCachedThreadPool();
final class MyTask implements Runnable {
#Override
public void run() {
System.out.println("Running my task.");
}
};
for (int i = 0; i < 10; ++i) {
service.submit(new MyTask());
}
service.shutdown();
service.awaitTermination(1, TimeUnit.DAYS);
}
Just dump your task into the service as many times as you want.
The ExecutorService is a thread pool - it has a number of Threads that take tasks as they come. This removes the overhead of spawning new Threads because it caches them.
Basically, a thread cannot be restarted.
So if you want a reusable "thread", you are really talking about a Runnable. You might do something like this:
Runnable myTask = new Runnable() {
public void run() {
// Do some task
}
}
Thread t1 = new Thread(myTask);
t1.start();
t1.join();
Thread t2 = new Thread(myTask);
t2.start();
(This is purely for illustration purposes only! It is much better to run your "runnables" using a more sophisticated mechanism, such as provided by one of the ExecutorService classes, which is going to manage the actual threads in a way that avoids them terminating.)
A java Thread cannot be run twice. Once it has been started and finished its work, it cannot be started again (calling method start will fail). So you'll have to create a new instance of Thread (using the same Runnable) and start it.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I am trying to print a statement in Java using threads, where each thread should print part of the statement. However, following code does not always output statement in correct order.
class NewThread implements Runnable {
String msg;
Thread t;
NewThread(String str) {
t = new Thread(this);
msg = str;
}
public void run() {
PrintMsg(msg);
}
synchronized void PrintMsg(String msg) {
System.out.println(msg);
try {
wait();
} catch (InterruptedException e) {
System.out.println("Exception");
}
System.out.println(msg);
notify();
}
}
class ThreadDemo {
public static void main(String args[]) {
NewThread t1, t2, t3;
t1 = new NewThread("Humphry Dumprey");
t2 = new NewThread("went to the hill");
t3 = new NewThread("to fetch a pail of water");
t1.t.start();
t2.t.start();
t3.t.start();
try {
t1.t.join();
t2.t.join();
t3.t.join();
} catch (InterruptedException e) {
System.out.println("Main Thread Interrupted");
}
}
}
I suspect problem with inter-thread communication.
I think your problem is in this method:
synchronized void PrintMsg(String msg) {
System.out.println(msg);
try {
wait();
} catch (InterruptedException e) {
System.out.println("Exception");
}
System.out.println(msg);
notify();
}
The thread that call it are going to call wait() which causes them to wait indefinitely for someone to call notify(). But there are no other calls to notify() so they all will stop there.
Also, because the method is synchronized each thread is also waiting on it's own NewThread instance. I think you meant to have all threads waiting and notifying on the same object?
From comments:
want to wait a thread until it finishes writing a part of statement. It should be like this : Thread 1 prints "Humphry Dumprey" Thread 2 prints "went to the hill" Thread 3 prints "to fetch a pail of water" and these three threads should execute in sequence such that the statement gets printed in right sequence.
I never understand these sorts of questions. The whole point of threads are that the run asynchronously in parallel. If you want them to print 3 things in a row then 1 thread should be used instead.
If you need to do this for some assignment then there a couple different ways you can do it.
Each thread could synchronize on the same AtomicInteger. Thread #1 would do its print if the integer was 1, thread #2 when it is 2, .... You could pass in the order as a value field to the NewThread constructor. After they print they values they increment the integer and notifyAll().
static final AtomicInteger counter = new AtomicInteger(1);
...
synchronized (counter) {
// looping like this is always recommended
while (counter.get() != value) {
counter.wait();
}
System.out.println(...);
counter.incrementAndGet();
counter.notifyAll();
}
You could use 2 CountdownLatch so thread #2 calls countDown1.await(); and thread #3 waits for countDown2.await();. Then after thread #1 prints its message it calls countDown1.countDown() and after thread #2 prints its message it calls countDown2.countDown().
I have a simple utility which pings a set of nodes and returns an ArrayList of strings to a future object to be outputted to a file. The program should run until terminated by the user.
It doesn't appear that the future receives the results (or at least passes them to the method to output to the file). No matter the number of threads I have concurrently running (always less than 100, determined by an input file), I am only outputting the results from the first and last initialized threads.
As a sanity check, I created a global variable in which each thread will send its results before closing and returning its results to the Future object. This variable is correctly updated by all threads.
Does anyone have any ideas why Future doesn't seem to be receiving all my results from the threads?
public class PingUtility{
public static ExecutorService pool = Executors.newFixedThreadPool(100);
static Future<ArrayList<String>> future;
public static void main(String[] args) throws Exception {
Timer timer = new Timer();
TimerTask task = new TimerTask(){
public void run(){
//Creates a pool of threads to be executed
ArrayList<String[]> nodes = new ArrayList<String[]>()
future = pool.submit(new PingNode(nodes));
}
}
};
timer.scheduleAtFixedRate(task, 0, interval);
while(true){
try{
ArrayList<String[]> tempOutputArray = future.get();
Iterator<String[]> it = tempOutputArray.iterator();
while(it.hasNext()) appendFile(it.next());
tempOutputArray.clear();
}catch(Exception nullException){
//Do nothing
}
}
}
Your problem is that you are modifying the future static field without synchronization in your timer-task thread(s) and reading it in the main thread. You need to either synchronize on it when you modify and read it or use another mechanism to share information between the threads.
I'd recommend switching from a static field to a LinkedBlockingQueue as a better way to send information from the PingNode call to the appendFile(...) method. This saves from needing to do the synchronization yourself and protects against the race conditions where multiple timer-tasks will start and overwrite the future before the consumer can get() from them. Maybe something like:
BlockingQueue<String[]> queue = new LinkedBlockingQueue<String[]>();
...
// inside of run, producer passes the queue into the PingNode
public void run() {
pool.submit(new PingNode(queue));
}
// consumer
while (true) {
String[] array = queue.take();
...
}
This doesn't take into effect how you are going to stop the threads when you are done. If the timer task is killed the entity could add to the queue a termination object to stop the main loop.
A Future object is not a bin, like an ArrayList, it merely points to a single computational result. Because you only have one static pointer to this Future, what I imagine is happening is this:
future = null
nullException
nullException
nullException
nullException
...
First thread finally sets future = Future<ArrayList<String>>
Call to future.get() blocks...
Meanwhile, all other threads get scheduled, and they reassign future
The last thread will obviously get the last say in what future points to
Data is gathered, written to file, loop continues
future now points to the Future from the last thread
Results from last thread get printed
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I am a newbie to the world of Threads and I am going through threads to latest util package reentrant lock mechanism, I was going through the basis differences between synchronize mechanism and the newly added lock mechanism , as in the article these were the differences..
Another significant difference between ReentrantLock and synchronized keyword is fairness. synchronized keyword doesn't support fairness. Any thread can acquire lock once released, no preference can be specified, on the other hand you can make ReentrantLock fair by specifying fairness property, while creating instance of ReentrantLock. Fairness property provides lock to longest waiting thread, in case of contention.Please if you could provide a small program which proves this point sp that I can grasp more
main difference between synchronized and ReentrantLock is ability to trying for lock interruptibly, and with timeout. Thread doesn't need to block infinitely, which was the case with synchronized, Please if you could provide a small program which proves this point sp that I can grasp more
One more worth noting difference between ReentrantLock and synchronized keyword in Java is, ability to interrupt Thread while waiting for Lock. In case of synchronized keyword, a thread can be blocked waiting for lock, for an indefinite period of time and there was no way to control that. ReentrantLock provides a method called lockInterruptibly(), which can be used to interrupt thread when it is waiting for lock. Similarly tryLock() with timeout can be used to timeout if lock is not available in certain time period.Please if you could provide a small program which proves this point sp that I can grasp more
Guys could you please provide a small program which shows all these above three points
I have tried this program , please advise what changes need to be done in it to prove above 3 points..
public class ReentrantLockHowto {
private final ReentrantLock lock = new ReentrantLock();
private int count = 0;
//Locking using Lock and ReentrantLock
public int getCount() {
lock.lock();
try {
System.out.println(Thread.currentThread().getName() + " gets Count: " + count);
return count++;
} finally {
lock.unlock();
}
}
//Implicit locking using synchronized keyword
public int getCountTwo() {
return count++;
}
public static void main(String args[]) {
final ThreadTest counter = new ThreadTest();
Thread t1 = new Thread() {
#Override
public void run() {
while (counter.getCount() < 6) {
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
ex.printStackTrace(); }
}
}
};
Thread t2 = new Thread() {
#Override
public void run() {
while (counter.getCount() < 6) {
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
};
t1.start();
t2.start();
}
}
Output:
Thread-0 gets Count: 0
Thread-1 gets Count: 1
Thread-1 gets Count: 2
Thread-0 gets Count: 3
Thread-1 gets Count: 4
Thread-0 gets Count: 5
Thread-0 gets Count: 6
Thread-1 gets Count: 7