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
Related
In my app I have 6 Arrays which should be updated each time my main activity starts. They all updated with main thread now and this leads to degradation in my app speed. Here is my dbUpdate() function:
private void dbUpdate(){
dateDB = getDateValues();
valueDB = getValues();
catDB = getCatValues();
catIndexDB = getCatIndex();
catExpenseDB = getCatExpense();
catLimitDB = getCatLimits();
}
These arrays have no dependency on eath other and I want to update them 6 parallel thread. I read this article and tried to put each array get function in a Runnable:
Runnable run6 = new Runnable(){
#Override
public void run(){
catLimitDB = getCatLimits();
}
};
So now I have six Runnable and one Handler and I changed my dbUpdate() function:
private void dbUpdate(){
hand.post(run1);
hand.post(run2);
hand.post(run3);
hand.post(run4);
hand.post(run5);
hand.post(run6);
}
But when I run my app I feel no difference. Can someone help me with this? And I should mention that this is my first experience with multithread programming.
if you really want to run them in parrallel you might do something like this:
new Thread(run1).start();
new Thread(run2).start();
new Thread(run3).start();
..
with the handler.post you add your jobs to a queue to the hanler - and your handler might be configured to run on the UI thread - so this might not be what you want.
This question already has answers here:
How to know if other threads have finished?
(12 answers)
Closed 8 years ago.
I have a method that can take time to complete as it uses the internet to check something and depending on the internet speeds can take a while so I have placed it into its own thread but I'm wanting to know how I can notice when this thread is complete as I then need to update the screen from the Main thread.
New thread code looks like this:
Thread newThread = new Thread(){
#Override
public void run() {
//My thread code
};
newThread.start();
This is what the thread code looks like, not going to copy and paste all the code it uses as it would be pointless but I'm wanting something like when
newThread.iscomplete {
//More code
}
Something along those lines
Thanks
Maybe you can show a message at the end of the Thread. Which would be helpful to let the user know that the process has finished.
Showing Message
System.out.print("Thread has finished!");
This would be at the last line, so it would only execute if all the above codes have been executed and the code has reached the last line for execution.
Thread newThread = new Thread() {
#Override
public void run() {
//My Thread code
System.out.print("Done!");
}
};
This will print Done! in the Console (I assume application is being run using a Console). Denoting that the code has been executed.
using a variable
boolean done = false;
Thread newThread = new Thread() {
#Override
public void run() {
//My Thread code
done = true;
}
};
Using EventListeners
Or else you can use Event Listener to detect the Thread completion. The above method was kind of simple.
http://docs.oracle.com/javase/tutorial/uiswing/events/
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 try to generate data set using multiple threads
I tried to create a Runnable and a couple of Threads in the following
public class DataGenerator {
static int currentRow = 0 ;
static PrintWriter pw ;
public static void main(String[] args) throws FileNotFoundException {
File file = new File("Test3.csv") ;
pw = new PrintWriter(file);
pw.println("var1,var2,var3") ;
Thread t1 = new Thread(new MyRunnable()) ;
Thread t2 = new Thread(new MyRunnable()) ;
t1.start();
t2.start();
t1.join();
t2.join();
pw.close();
System.exit(0) ;
}
}
class MyRunnable implements Runnable {
public void run () {
for ( int i = DataGenerator.currentRow; i < 50000000; DataGenerator.currentRow ++ ) {
DataGenerator.pw.println(i + ",19:05.1,some text");
System.out.println(i);
}
}
}
However is looping over o
I cant find out why
When you start a thread it leaves the thread to start up in its own thread. So what is happening is, its starting the thread and then going straight to the next call pw.close() before the thread has had a chance to start up.
Your parent thread is closing the PrintWriter pw before the child Threads t1 and t2 can use it to print. You need to have your parent thread call wait() after you've started your child Threads.
You should review the answer to How to make a Java thread wait for another thread's output? for some help. You can use this information to discover how to solve this issue from a code-standpoint; it's fairly simple.
Note: you have edited your question since this answer was posted; the answer to the following question is even more relevant: Wait until child threads completed : Java
Other useful SO questions with applicable answers that you should read:
A simple scenario using wait() and notify() in java
How to use wait and notify in Java?
Wait function in Java
Java Wait Function
Wait() / notify() synchronization
See also Java Concurrency Tutorial.
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.