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.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am currently learning basics of Threads in Java and I am trying to write a simple Thread Group program. I wrote it same as tutorial website though i'm getting different type of output. Below is my code for which i'm getting different output.
public class ThreadGroupDemo implements Runnable {
#Override
public void run() {
System.out.println(Thread.currentThread().getName());
// get the name of the current thread.
}
public static void main(String[] args) {
ThreadGroupDemo runnable = new ThreadGroupDemo();
ThreadGroup tg1 = new ThreadGroup("Parent Group");
// Creating thread Group.
Thread t1 = new Thread(tg1, new ThreadGroupDemo(), "one");
t1.start();
t1.setPriority(Thread.MAX_PRIORITY);
Thread t2 = new Thread(tg1, new ThreadGroupDemo(), "second");
t2.start();
t2.setPriority(Thread.NORM_PRIORITY);
Thread t3 = new Thread(tg1, new ThreadGroupDemo(), "Three");
t3.start();
System.out.println("Thread Group name : " + tg1.getName());
tg1.list();
}
}
I am getting
Output :
Thread Group name : Parent Group
Three
java.lang.ThreadGroup[name=Parent Group,maxpri=10]
second
one
Thread[one,10,Parent Group]
Thread[second,5,Parent Group]
Thread[Three,5,Parent Group]
The output should be like :
one
two
three
Thread Group Name: Parent ThreadGroup
java.lang.ThreadGroup[name=Parent ThreadGroup,maxpri=10]
Thread[one,5,Parent ThreadGroup]
Thread[two,5,Parent ThreadGroup]
Thread[three,5,Parent ThreadGroup]
i am not able to understand why this happening? setting Priority can help with it?
You can't predict the order of executions of your threads even with a level of priority. You have no control on the scheduling. It's your OS which decides.
A good book about concurrency in Java : Java concurrency in practice
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have some questions about java threads:
if I have a class that runs a number of threads when one thread reaches to exit(1) command line will it exit the thread or the whole application including the other threads?
2.how can I make one thread notify all other threads that run from the same class to stop?
3.does using synchronized make only one thread ,regardless his source in the code, to do this part of code?
4.if I am running a thread in java using run() if I call a method from inside the run() does this still running as a thread or it is not allowed?
1) Only if thread are daemons, application will not wait to close even if they are running.
Example: comment or not the setDaemon(true)
public class Test {
public static void main(final String[] args) {
new Launcher(parent).start();
}
public static class Launcher extends Thread {
public Launcher(final String name) {
this.setName(name);
}
#Override
public void run() {
System.err.println(getName() + is starting);
for (int i = 0; i < 10; i++) {
new Waiter(child + i).start();
}
try {
Thread.sleep(1000);
System.err.println(getName() + is no more sleeping);
} catch (final InterruptedException e) {
e.printStackTrace();
}
System.err.println(getName() + is stopping);
}
}
public static class Waiter extends Thread {
public Waiter(final String name) {
super(name);
super.setDaemon(true);
}
#Override
public void run() {
System.err.println(getName() + is starting);
try {
Thread.sleep(12000);
System.err.println(getName() + is no more sleeping);
} catch (final InterruptedException e) {
e.printStackTrace();
}
}
}
}
2) To force the stop, you can use different approach, different patterns. Sorry to not have THE solution. You can take a look at : http://docs.oracle.com/javase/7/docs/api/java/lang/ThreadGroup.html
3) Yeah, it's the goal of synchronized.
4) It depends what you do but basically, calling a method do not launch another thread, except if the methods does it.
if I have a class that runs a number of threads when one thread reaches to exit(1) command line will it exit the thread or the whole application including the other threads?
A call to System.exit(1) will terminate the calling thread and all other threads. It is the most brutal way of ending a Java program, namely completely shutting down the JVM, and should rarely be used at all.
how can I make one thread notify all other threads that run from the same class to stop?
Not at all. If you have references to the other Thread objects, you can call Thread#interrupt(), but whether or not the other threads check their interrupted status or reach a place where they may throw an InterruptedException is left to them.
does using synchronized make only one thread ,regardless his source in the code, to do this part of code?
Intuitively yes. However, when there is a wait() in this block, then the corresponding lock (that is, the object that was synchronized on) will be released and can be acquired by other threads.
if I am running a thread in java using run() if I call a method from inside the run() does this still running as a thread or it is not allowed?
When a thread calls a method, then the same thread also executes this method (silently wondering how else it should be...)
I think I'm having race conditions when running my multithreaded Java program.
It's a permutation algorithm, which I want to speed up by running multiple instances with different values. So I start the threads in Main class with:
Runnable[] mcl = new MCL[n1];
for (int thread_id = 0; thread_id < n1; thread_id ++)
{
mcl[thread_id] = new MCL(thread_id);
new Thread(mcl[thread_id]).start();
Thread.sleep(100);
}
And it runs those MCL classes instances.
Again, I think threads are accessing the same memory space of the MCL class variables, am I right? If so, how can I solve this?
I'm trying to make all variables arrays, where one of the dimensions is related to an Id of the thread, so that each thread writes on a different index. Is this a good solution?:
int[] foo = new foo[thread_id];
You can't just bolt on thread safety as an afterthought, it needs to be an integral part of your data flow design.
To start, research and learn the following topics:
1) Synchronized blocks, mutexes, and final variables. A good place to start: Tutorial. I also love Josh Bloch's Effective Java, which although a few years old has golden nuggets for writing correct Java programs.
2) Oracle's Concurrency Tutorial
3) Learn about Executors. You shouldn't have to manage threads directly except in the most extreme cases. See this tutorial
If you pass non thread safe objects between threads you're going to see unpredictable results. Unpredictable means assignments may never show up between different threads, or objects may be left in invalid states (especially if you've got multiple member fields that have data dependent on each other).
Without seeing the MCL class we can't give you any specific details on what's dangerous, but given the code sample you've posted I think you should take a step back and do some research. In the long run it will save you time to learn it the right way rather than troubleshoot an incorrect concurrency scheme.
If you want to keep the thread data separate store it as instance variables in the Runnables (initializing each Runnable before starting its thread). Don't keep a reference to it in an array, that's just inviting trouble.
You can use a CompletionService to get a computed value back for each task wrapped in a Future, so you don't wait for it to be calculated until you actually need the value. The difference between a CompletionService and an Executor, which the commentors are recommending, is that the CompletionService uses an Executor for executing tasks, but it makes it easier to get your data back out, see this answer.
Here's an example of using a CompletionService. I'm using Callable instead of Runnable because I want to get a result back:
public class CompletionServiceExample {
public static void main(String[] args) throws Exception {
ExecutorService executorService = Executors.newCachedThreadPool();
ExecutorCompletionService<BigInteger> service =
new ExecutorCompletionService<BigInteger>(executorService);
MyCallable task1 = new MyCallable(new BigInteger("3"));
MyCallable task2 = new MyCallable(new BigInteger("5"));
Future<BigInteger> future1 = service.submit(task1);
Future<BigInteger> future2 = service.submit(task2);
System.out.println("submitted tasks");
System.out.println("result1=" + future1.get() );
System.out.println("result2=" + future2.get());
executorService.shutdown();
}
}
class MyCallable implements Callable<BigInteger> {
private BigInteger b;
public MyCallable(BigInteger b) {
this.b = b;
}
public BigInteger call() throws Exception {
// do some number-crunching thing
Thread.sleep(b.multiply(new BigInteger("100")).longValue());
return b;
}
}
Alternatively you can use the take method to retrieve results as they get completed:
public class TakeExample {
public static void main(String[] args) throws Exception {
ExecutorService executorService = Executors.newCachedThreadPool();
ExecutorCompletionService<BigInteger> service = new
ExecutorCompletionService<BigInteger>(executorService);
MyCallable task1 = new MyCallable(new BigInteger("10"));
MyCallable task2 = new MyCallable(new BigInteger("5"));
MyCallable task3 = new MyCallable(new BigInteger("8"));
service.submit(task1);
service.submit(task2);
service.submit(task3);
Future<BigInteger> futureFirst = service.take();
System.out.println(futureFirst.get());
Future<BigInteger> futureSecond = service.take();
System.out.println(futureSecond.get());
Future<BigInteger> futureThird = service.take();
System.out.println(futureThird.get());
executorService.shutdown();
}
}
So say that I have 10 things to run, but I can only have 3 threads running at a time.
ArrayList<NewThread> threads = new ArrayList<NewThread>();
for(int i = 1; i < args.length; i++) {
NewThread t = new NewThread(args[i]);
threads.add(newThread);
if( (i%3) == 0) {
for (NewThread nt : threads) {
nt.join();
}
threads.clear();
}
}
The class NewThreads implements Runnable. I thought the join() method would work to make it wait for the threads to finish before looping around again and kicking off the next batch of threads, but instead I get a stack overflow exception. I think I am implementing join() incorrectly, but I am unsure how to do it. I currently am doing it as
public void join() {
this.join();
}
in my NewThread class. Any suggestions on how to get this working or a better way to go about it?
You are implementins or overriding join to call itself endlessly
public void join() {
this.join(); // call myself until I blow up.
}
The simplest solution is to use Thread.join() already there, but a better solution is to use a fixed size thread pool so you don't have to start and stop threads which can waste a lot of time and code.
You can use an ExecutorService
ExecutorService es = Executors.newFixedThreadPool(3);
for(int i=0;i<10;i++)
es.submit(new Task(i));
This is just a simple mistake.
Remove the method
public void join() {
this.join();
}
This method calls itself again and again.
NewThread should extend Thread.
Or 2nd way:
keep the method and call
Thread.currentThread.join();
The rest looks fine.
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.