I have a portion of code dealing with threads and I want to understand its function in detail. The run method is empty in my example, but lets assume it has some operations to do on a global variable:
import java.io.File;
public class DigestThread extends Thread {
private File input;
public DigestThread(File input) {
this.input = input;
}
public void run() {
}
public static void main(String[] args) {
for (int i = 0; i < args.length; i++) {
File f = new File(args[i]);
Thread t = new DigestThread(f);
t.start();
}
}
}
After creating a thread and starting it, will it wait to finish the tasks in the run method before creating/running another thread ?
second question
if a variable has declared in run method that means it will be declared many times because every thread created will do the task in run method , is every thread handles its own varible although variable in each thread are same ?
will it waitng for finish the tasks in run method to creat another
method ?
No. That's the whole point of Multithreading. Every thread has it's own stack of execution. So, when you start a thread, it enters the run() method, and executes it in a different stack, and at the same time the main thread continues execution, in it's own stack.
After that, main thread, can spawn another thread. Thus all the threads run simultaneously, but of course, one at a time, sharing the CPU amongst them, based on the specific CPU allocation algorithm being used.
It's not possible to write down all the details about the execution process of multiple threads here. I would rather suggest to read some tutorials or search for some online resources, regarding the concept of Multithreading. Once clear in concept, move ahead with the implementation in Java.
Here's some tutorials links you can start with: -
Thread Wiki Page
SO Multithreading Wiki Page
Concurrency - Oracle Tutorial
http://www.vogella.com/articles/JavaConcurrency/article.html
Once you start a thread, it will run in a separate thread and the main() thread will continue (it may end before the child thread ends).
If you want the thread to finish before main then you can use the Thread.join method on thread to wait for it.
First, Thread is a single sequential flow of control within a program.
We can execute more than one thread in a program, but there is a life cycle, where you can find out how threads work...
Whenever we call the start() method of Thread it automatically calls the overriden method public void run() and executes the code of the run() method...
Here is a simple example of Thread in Java with ABC and XYZ thread classes
/* Write a program to print having two Thread Class 1) ABC with 1 second 2) XYZ 2 second. 10 times with Extend Constructor */
class ABCThreadConstructor extends Thread {
ABCThreadConstructor(String name) {
super(name);
}
public void run() {
try {
for(int i = 0; i < 10; i++) {
System.out.println("ABC");
Thread.sleep(1000);
}
} catch(InterruptedException ie) {
System.out.println("Interrupted Exception : "+ie);
}
}
}
class XYZThreadConstructor extends Thread {
XYZThreadConstructor(String name) {
super(name);
}
public void run() {
try{
for(int i = 0; i < 10; i++) {
System.out.println("XYZ");
Thread.sleep(2000);
}
} catch(InterruptedException ie) {
System.out.println("Interrupted Exception : "+ie);
}
}
}
class AbcXyzThreadConstructorDemo {
public static void main(String args[]) {
ABCThreadConstructor atc = new ABCThreadConstructor("ABCThreadConstructor");
System.out.println("Thread Name : " + atc.getName());
atc.start();
XYZThreadConstructor xtc = new XYZThreadConstructor("XYZThreadConstructor");
System.out.println("Thread Name : " + xtc.getName());
xtc.start();
}
}
Assuming your question is "After creating a thread and starting it, will the program wait for the thread to finish its run method before creating another thread?"
If that's the case, No the program will not wait. t.start() kicks off the thread and it gets its own chunk of memory and thread priority to run. It will do its operations and then exist accordingly. Your main thread will start the number of threads specified in args before terminating.
If you need the application to wait on the thread then use t.join(). That way the parent thread (the one that runs main) will be joined to the child thread and block until its operation is complete. In this case it sort of defeats the purpose of threading but you can store the thread ID for whatever logic you need and join() later.
Related
When using while(true) loop in main thread with Thread.sleep() the child threads works fine but if i remove sleep method from while loop the child threads do not work. I mean, thread defines parallelism so it should work ?
public static void main(String[] args) {
Thread th1 = new Thread(new Runnable() {
#Override
public void run() {
for (int i=0; i<50; i++) {
System.out.println("I love java.");
Thread.sleep(500);
}
}
});
th1.start();
th2.start(); // Similarly assume thread 2
// Here's my main thread
while(true) {
System.out.println("I am main thread.");
// If i use Thread.sleep(200) here, works fine but if not the child thread do not
print messages
}
}
I am new to java, so might be the question is bit silly. Answers will be helpful.
No, it works fine on both situations.
when you use Thread.sleep() in main-thread the main thread executes slower, thus you can see the "I love java" message (because t1 executes first)
when you don't use Thread.sleep() the main thread executes faster, so you can't see the "I love java" message. but it is there (on the first or second line of output)
debug the program to see more information. debugging shows the number of threads running currently and many more information
If you want to learn more about concurrency(multithreading) visit the link
https://www.baeldung.com/java-concurrency
From what i read here Thread join on itself ;
When join method is called on itself, it should wait forever
I am currently preparing for ocajp 8 certification,for which going through dumps and when i got this question ,what i thought is main should wait forever
public class startinginconstructor extends Thread
{
private int x=2;
startinginconstructor()
{
start();
}
public static void main(String[] args) throws Exception
{
new startinginconstructor().makeitso();
}
public void makeitso() throws Exception
{
x=x-1;
System.out.println(Thread.currentThread().getName()+" about to call join ");
join();
System.out.println(Thread.currentThread().getName()+" makeitso completed ");
// above line shouldn't be executed (method shouldn't be completed as well )since it joined on itself..?
}
public void run()
{
System.out.println(Thread.currentThread().getName()+" run started ");
x*=2;
System.out.println(Thread.currentThread().getName()+" run about to complete ");
}
}
program ended with following output
main about to call join
Thread-0 run started
Thread-0 run about to complete
main makeitso completed
Did i wrongly get the meaning of thread waiting forever or is there something i am missing
note: I know starting thread from constructor is not a recommended practice.. this is exact question in the dumps so i just pasted it (* not pretty much exact actually,i have placed println statements to see flow of the program)
There is no thread that joins itself in your example.
The main() thread in your example creates a new thread and then it joins the new thread.
Don't confuse Thread (i.e., the java object) with thread (the execution of the code.) All of your methods belong to the same Thread object, but they run in two different threads.
James is correct (+1 from me), I'm just trying to make this more explicit. Here is what happens:
Your main thread constructs the startinginconstructor constructor.
The constructor calls start, which will result in the startinginconstructor object having its run method in the new thread.
After that the main thread will proceed to call makeitso. In makeitso this is the startinginconstructor object, so the result is that the main thread waits until the thread represented by the startinginconstructor object has finished.
Java objects can be called by any thread, just because an object extends Thread doesn't mean any invocation of that method is happening on that thread.
Below is my sample code, when my a.start() called it should create a thread and print "Run" immediately. But why does is called after printing "begin" 20 times.
How does thread "a" decide that it doesn't have to call run() immediately.
public class JoinTest implements Runnable {
public static void main(String[] args) throws InterruptedException {
Thread a = new Thread(new JoinTest());
a.start();
for (int i = 0; i < 20; i++) {
System.out.print("Begin");
}
Thread.sleep(1000);
a.join();
System.out.print("\nEnd");
}
public void run() {
System.out.print("\nRun");
}
}
Output:
BeginBeginBeginBeginBeginBeginBeginBeginBeginBeginBeginBeginBeginBeginBeginBeginBeginBeginBeginBegin
Run
End
I am little confused about the behavior of thread.
In my opinion "run" should be printed before "begin" because it get printed before the join() method is called, and at the time of join method called thread "a" must have finished its execution and calling join must be useless at that point.
Calling start() on a thread doesn't necessarily triggers the execution of its run() method immediately. Your thread is marked as started but the main thread pursues its execution into the for loop. Then the JVM is switching to your thread once the main thread reaches the sleep() statement.
You start the thread, then immediately do some printing, then sleep. Looking at your code I would actually expect to see Begin before Run because the thread is being started in the background, concurrently to your main thread going on with its work. Futhermore, the print method is synchronized so you repeatedly acquire that lock in a loop, giving even less chance to the second thread to interject.
I have tried your code with Thread.sleep eliminated, both with and without the join call. The behavior is the same in both cases: Run comes at the end most of the time and occasionally manages to get interleaved between the Begin words. Everything exactly as expected by the simple model of concurrency with synchronized blocks.
Here is a slight variation on your code which reliably prints Run before everything else, whether you call the join method or not. All that changed is the position of the sleep call.
public class JoinTest implements Runnable
{
public static void main(String[] args) throws InterruptedException {
Thread a = new Thread(new JoinTest());
a.start();
Thread.sleep(1000);
for (int i = 0; i < 20; i++) {
System.out.print("Begin");
}
a.join();
System.out.print("\nEnd");
}
public void run() {
System.out.print("\nRun");
}
}
The start() method calls the thread's run() method, although this takes a little time, which may just be enough for some or all of your 'Begin' loops to complete. When I run this on my machine the 'Run' output appears between the first and second 'Begin'. Try outputting with timestamps so you can see how long your machine is taking to execute each command:
public class JoinTest implements Runnable {
public static void main(String[] args) throws InterruptedException {
Thread a = new Thread(new JoinTest());
a.start();
for (int i = 0; i < 20; i++) {
System.out.println("Begin " + System.nanoTime());
}
Thread.sleep(1000);
a.join();
System.out.println("End " + System.nanoTime());
}
public void run() {
System.out.println("Run " + System.nanoTime());
}
}
Calling a.join() at that point ensures that you will always see 'Run' output before 'End', as join() waits for the thread to complete.
I have tried many scenarios with join(), "run" always get printed after "begin" but when i remove the join statement "run" always get printed before "begin". Why?
Because it's allowed. That's why. As soon as you call .start(), you have two threads. Untill your program calls a synchronization methods like .join() it's entirely up to the JVM implementation and the operating system to decide which thread gets to run when.
The a.join() call from your main thread forces the main thread to wait until the a thread has completed its run() method.
Without the a.join() call, the Java Language Specification permits the a thread to complete its work before a.start() returns in the main thread, and it permits the main thread to reach the end of the main() function before the a thread even begins to run, and it permits anything in between to happen.
It's entirely up to the JVM and the OS.
If you want to take control of the order in which things happen, then you have to use synchronized blocks, and synchronization objects and method (e.g., .join()).
But beware! The more you force things to happen in any particular order, the less benefit your program will get from using threads. It's best to design your program so that the threads can function independently of one another most of the time.
Practicing multi thread java examples ,here i am creating thread A in class A and thread B in class B .Now starting those two threads by creating objects .here i am placing the code
package com.sri.thread;
class A extends Thread
{
public void run()
{
System.out.println("Thread A");
for(int i=1;i<=5;i++)
{
System.out.println("From thread A i = " + i);
}
System.out.println("Exit from A");
}
}
class B extends Thread
{
public void run()
{
System.out.println("Thread B");
for(int i=1;i<=5;i++)
{
System.out.println("From thread B i = " + i);
}
System.out.println("Exit from B");
}
}
public class Thread_Class
{
public static void main(String[] args)
{
new A().start(); //creating A class thread object and calling run method
new B().start(); //creating B class thread object and calling run method
System.out.println("End of main thread");
}
//- See more at: http://www.java2all.com/1/1/17/95/Technology/CORE-JAVA/Multithreading/Creating-Thread#sthash.mKjq1tCb.dpuf
}
i didn't understand the flow of execution ,tried by debugging but didn't get it.how the flow of execution is .Here i am placing the out put which confusing me.
Thread A
Thread B
End of main thread
From thread B i = 1
From thread B i = 2
From thread B i = 3
From thread B i = 4
From thread B i = 5
Exit from B
From thread A i = 1
From thread A i = 2
From thread A i = 3
From thread A i = 4
From thread A i = 5
Exit from A
Why does the loop in thread B finish before the loop in thread A is entered?
Unless you have multiple processors, the threads are sharing a processor on a time slice basis. The total time to execute one of your threads may be less than the time slice, so whichever thread gets dispatched first will complete before the other runs at all.
Try adding a short Thread.sleep call in the run methods.
There really is no guaranteed order of execution when executing multiple threads. The threads are independent of each other.
The link in the source code explains it:
Here you can see that both outputs are different though our program
code is same. It happens in thread program because they are running
concurrently on their own. Threads are running independently of one
another and each executes whenever it has a chance.
The threads are executing at the same time. One isn't executing inside the other. Each thread gets CPU time, does some work, and then waits while the CPUs are busy with other things. It could run differently each time depending on what else is happening on the computer.
If you expected the threads' output messages to be interlaced, they will be, to an extent, if you increase your loops to several thousands of iterations. Right now the code finishes so quickly it's hard to see that they really are running in parallel.
I'm having a-bit of trouble with threads in java. Basically Im creating an array of threads and starting them. the point of the program is to simulate a race, total the time for each competitor ( i.e. each thread ) and pick the winner.
The competitor moves one space, waits ( i.e. thread sleeps for a random period of time between 5 and 6 seconds ) and then continues. The threads don't complete in the order that they started as expected.
Now for the problem. I can get the total time it takes for a thread to complete; what I want is to store all the times from the threads into a single array and be able to calculate the fastest time.
To do this should I place the array in the main.class file? Would I be right in assuming so because if it was placed in the Thread class it wouldn't work. Or should I create a third class?
I'm alittle confused :/
It's fine to declare it in the method where you invoke the threads, with a few notes:
each thread should know its index in the array. Perhaps you should pass this in constructor
then you have three options for filling the array
the array should be final, so that it can be used within anonymous classes
the array can be passed to each thread
the threads should notify a listener when they're done, which in turn will increment an array.
consider using Java 1.5 Executors framework for submitting Runnables, rather than working directly with threads.
EDIT: The solution below assumes you need the times only after all competitors have finished the race.
You can use a structure that looks like below, (inside your main class). Typically you want to add a lot of you own stuff; this is the main outline.
Note that concurrency is not an issue at all here because you get the value from the MyRunnable instance once its thread has finished running.
Note that using a separate thread for each competitor is probably not really necessary with a modified approach, but that would be a different issue.
public static void main(String[] args) {
MyRunnable[] runnables = new MyRunnable[NUM_THREADS];
Thread[] threads = new Thread[NUM_THREADS];
for (int i = 0; i < NUM_THREADS; i++) {
runnables[i] = new MyRunnable();
threads[i] = new Thread(runnables[i]);
}
// start threads
for (Thread thread : threads) {
thread.start();
}
// wait for threads
for (Thread thread : threads) {
try {
thread.join();
} catch (InterruptedException e) {
// ignored
}
}
// get the times you calculated for each thread
for (int i = 0; i < NUM_THREADS; i++) {
int timeSpent = runnables[i].getTimeSpent();
// do something with the time spent
}
}
static class MyRunnable implements Runnable {
private int timeSpent;
public MyRunnable(...) {
// initialize
}
public void run() {
// whatever the thread should do
// finally set the time
timeSpent = ...;
}
public int getTimeSpent() {
return timeSpent;
}
}