Current Thread Method java - java

So I am trying to work with threads for a game I am making. I am very new to the subject so I may not understand correctly. My question is how does the currentThread() method work in the Thread class of the java API. The API says "Returns a reference to the currently executing thread object.", but as far as I understand multiple threads run at the same time. How is it possible to return only one executing thread?

The code that calls currentThread will be executing in one of the threads, not in all of them, so it can get that thread specifically.

Suppose you have list of instructions printed on a piece of paper. A person reads the instructions and performs them. The instructions are a program. The person is a thread. You could make many copies of the paper and pass them out to many people. If the instructions say something like, "slap yourself," yourself refers to whomever is reading that instruction from that paper. Likewise, Thread.currentThread() refers to the thread that is executing that call to currentThread().

When an instruction in your code is executed, it is executed within a specific thread. This is the thread returned by that method.
Obviously, if a specific method is executed by multiple threads, each execution might return a different value for Thread.currentThread().
You could try this short example to get a better idea of what is going on and in particular the fact that the 2 threads execute in parallel. You should see that t1 will run a few loop then t2 will do the same and back to t1 etc (you might need to increase the number of loops from 5 to a higher number depending on your machine):
public class TestThread {
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread());
}
}
};
Thread t1 = new Thread(r, "t1");
Thread t2 = new Thread(r, "t2");
t1.start();
t2.start();
}
}

"The currently executing thread" means that the system scheduler gave some time to this thread to execute its code.

When writing a single threaded application, you can reason on your program like a series of instruction, each executed after the previous one is finished (this is a rough approximation, but conceptually compilator and processor try to simulate that and work as if this was really what was happening).
When you use multiple thread, each thread has its own series of instruction. A new thread when created is passed a entry point (a method), and will continue executing from them. Each thread is independent from the other thread in their execution (it will simply execute one instruction after the other), though they share memory and thus side-effect from one thread can affect another.
So for some code to be executed, it must be done in the context of one thread (there is one created by the operating system when your application start, that start its execution at the Main method). When the function currentThread is called, it is in one of those context.
The java runtime when creating a thread will store a reference to that Thread object in the thread context, and the currentThread will just lookup there and return the current thread.

At any given point in time, only one thread will be executing(live), so Thread.currentThread() returns the details of the currently executing Thread. e.g., Thread_name, priority, method_name.

Multiple threads are not running at the same time and there is thread switching between multiple threads. Processor can execute one task at a time so one thread at a a time executed. So we get the reference of currently running thread.

Related

Java multithreading: setPriority()

I was reading online about Thread's setPriority() and came across the following:
final void setPriority(int level)
Here, level specifies the new priority setting for the calling thread.
Source:http://www.java-samples.com/showtutorial.php?tutorialid=302
What I don't understand is how setPriority() alters the priority for the calling thread: shouldn't it affect the object on which it is invoked, the callee? So if I call the method from main(), then main()'s priority will be altered? This sure looks to me as counter-intuitive.. .
That is unless I don't understand what's meant by a calling thread.. .
Every piece of code in Java is executed from an instance of a Thread.
If you do not write your own threads everything will be executed by a java-main-thread.
When a Java Virtual Machine starts up, there is usually a single non-daemon thread (which typically calls the method named main of some designated class). (from the Java API for Thread)
However you can use multiple Threads across your project to make usage of multi-threading and parallelism technology on your machine.
The method setPriority can be used to give the current thread object on which you are calling this method a priority. This priority is used by the thread scheduler of your OS to give the threads CPU time based on their priorities. So a thread with higher priority is more likely to get CPU time than one with a smaller priority.
Again, if you are not using any self made threads you are indeed using a java-main-thread. You can always access the current thread you are in by using Thread.getCurrentThread().
So if you have your own Thread class MyOwnThread extends Thread and write something like this:
MyOwnThread myOwnThread = new MyOwnThread();
myOwnThread.setPriority(...);
The priority of the myOwnThread is affected. But if you write something like this:
public static void main(String[] args) {
...
Thread.getCurrentThread().setPriority(...);
...
}
You are affecting the java-main-thread.
The methid setPriority is defined in Thread.java https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#setPriority(int)
Priority is helpful hint for thread scheduler to decide which thread to give priority while allocating CPU. By default Main thread starts the execution of a java program. Developers can create their custom Thread.java's objects. When these threads are started then the code initiated by the run method of the thread executes in its path of execution of that particular thread. Each thread is backed by a method call stack. The default priority of the Main thread is 5. Any thread created is provided with the priority value same as of the thread in whose execution path it is created.
You need an object on which you can invoke (call) a method upon.
What do you mean when you say "...if I call the method from main(),..." ? You just cant call it without any instance of thread. You can create an instance of a Thread and then invoke the method setPriority on it. Doing this will set the priority of the thread upon which you invoke the method.
Thread usedDefinedThreadReference = new Thread();
usedDefinedThreadReference.setPriority(2);
Above will create an instance of the thread and set its priority equal to the currently executing thread , if its main thread then by default its priority is set to 5.
Thread.currentThread().setPriority(6);
Above will set the priority of the currently executing thread as 6.
public static void main(String[] args){
Thread.currentThread().setPriority(7); // currently executing thread is Main thread and its priority is set as 7 from its default value of 5
Thread t = new MyThread(); // its priority is set to 7 as current executing thread has priority equal to 7.
t.setPriority(3); // priority of Thread object referenced by t is set to 3.
Thread.currentThread().setPriority(8); // main thread is currently executing thread hence its priority is set as 8.
}
public class MyThread extends Thread {
public Thread(){
Thread.currentathread().setPriority(9); // Main thread is currently executing thread hence its priority is set as 9.
this.setPriority(8); // this refers to object of MyThread , the current object hence its priority is set as 8 not of main.
}
public void run(){
Thread.currentThread().setPriority(2); // currently executing thread is MyThread`s object hence its priority is set as 2.
this.setPriority(4); // again currently executing thread is Object of MyThread hence its priority is set as 4.
}
}
The really important part here: priorities are only a recommendation to the underlying operating system.
In other words: the results of using Thread priorities in Java fully depend on things as JVM version, OS type, OS version, ...
Long story short: relying on them is a waste of time. Because chances are very close to zero that using this concept will lead to the expected results.
[ personal opinion here: I recently spend hours trying to write priority-based Java threads just to show the effects of priorities - didn't work out; neither for Windows, nor for Linux ]

Do two threads started in consecutive statements run at the same time, or do they run one after another?

Look at the following code. All the statements in this snippet are being executed in the main thread.
Threads are separate units of execution, i.e. two different threads can be executing simultaneously, independent of each other, right?
So does it mean that the statement new Thread(new Consumer()).start(); will be executed once the new Thread(new Producer()).start(); statement's execution is complete (that is when the Producer thread is done with execution, that is after the run() method of Producer has returned)?
Or does the JVM simply gets to and starts executing the new Thread(new Consumer()).start(); statement, right after it has invoked the start() method of the first thread, i.e. while the first Producer thread is running?
public class ThreadsCoordinationUsingGuardedBlocks {
public static void main(String[] args) {
new Thread(new Producer()).start();
new Thread(new Consumer()).start();
}
}
two different threads can be executing simultaneously, independent of each other, right?
They also start independently which means they can start in any order and if one completes quickly it could stop before other has even had a chance to start.
after the run() method of Producer has returned)?
So that is possible, it is also possible the threads will complete in the opposite order.
Or does the JVM simply gets to and starts executing the new Thread(new Consumer()).start(); statement,
Note: the JVM doesn't implement the threads. This is the job of the OS. All Java does is make system calls to the OS to tell it to do that. The JVM has no idea how long after start() is called that the run() of those threads will be called.
You should assume that the order is non-deterministic. Thread() is probably a schedulable event, so even on a uni-processor there is no guarantee of the order of execution and you may be running on a multi-processor as well.
Your code should explicitly handle synchronization – even if some quirk of the implementation where you run causes deterministic execution, explicit synchronization serves to communicate the intent of your code and guards against a change in the underlying thread code.

Why is there a limitation to start a Thread in JAVA only once even if the thread is completed its execution and terminated [duplicate]

I was reading about threads and found that we can't call the start method twice on the same thread instance. But I didn't understand the exact reason for the same. So why can't we call it twice or even more times?
In my opinion the Thread object is your "handle" for the actual running context. If you allow creating many concurrent executions associated with the same java.lang.Thread, what would you expect getStackTrace() and getState() methods to return?
I suppose that Thread class could have been designed to allow spawning multiple running contexts, but its API would be less simple and clean.
You want 1 instance for 1 thread, as that thread has internal state it will manage.
Consider threads as a kind of resource. It usually does not make sense to have 1 instance refer to several resources - (just as you can't have a java File object refer to more than 1 file).
It would also get you in all sorts of trouble if you started a thread twice, and you either inherited from Thread and made some instance variables that now more than 1 thread accesses, - same thing if you create the thread from a Runnable. Atleast the API doesn't make it a no-brainer to do that screw-up.
Take a look at the states a thread can be in , here http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Thread.State.html
Basically, the only time you can start a thread is when it is in the NEW state. And none of the other states can make it transition back to NEW
A Thread is not the same thing as a thread.
A (little-t) thread is an independent execution of your code. A (Big-T) Thread is a Java object that can be used to start, and manage the life cycle of a little-t thread.
Suppose you were hired to write code for an insurance company, and you defined a (Big-A) Accident class to represent a (little-a) accident. Somebody asks you, "Why can't I re-use an Accident instance?"
Well, an accident can only happen once, right? Even if the exact same thing happens to the exact same drivers and cars in the exact same way on a different day, it's still a different accident, right?
according to thread life cycle, once thread is 'dead' you can not restart it.You only can start new thread invoking start() method.
Thread can be bought to Running state from Runnable state not from Dead state.
This is my opinion, It is due to Thread id. Thread scheduler is identifying the thread through the thread id. It is unique real number. Please find below code,
public class StartTwice extends Thread {
public void run() {
System.out.println("running...");
}
public static void main(String[] args) {
StartTwice start1 = new StartTwice();
System.out.println("Thread id: " + start1.getId());
start1.start();
start1 = new StartTwice();
System.out.println("Thread id: " + start1.getId());
start1.start();
}
}
Output is:
Thread id: 10
Thread id: 11
running...
running...
When I re-instantiate the start1 object. A new thread id is created.
PS: Even a thread is done, we can't use the same object (thread id) second time.
Until or unless the JVM is reuse that id.

will main thread exit before child threads complete execution? [duplicate]

This question already has answers here:
termination of program on main thread exit?
(2 answers)
Closed 7 years ago.
will main thread exit before child threads complete execution?
i read in 2 articles
http://www.cs.mtu.edu/~shene/NSF-3/e-Book/FUNDAMENTALS/thread-management.html
in the above article, In "Thread Termination" para, it states in Red " if the parent thread terminates, all of its child threads terminate as well."
http://www.roseindia.net/java/thread/overview-of-thread.shtml
in the above article, the last line in that page states "The main() method execution can finish, but the program will keep running until the all threads have complete its execution.".
i fee they are contradictory. if i am wrong, Please experts correct me.
In my program, a program with Main method calls the constructor of 2 threads . in the constructor of the respective threads, i am having the start() method .
TestA A = new TestA("TestA");
TestB B = new TestB("TestB");
public TestA(String name) {
System.out.println(name);
t = new Thread(this);
t.start();
}
i would like to know what happens, main thread terminates before child threads complete execution? if so, will the child threads anyway, continue their execution??
i tried running the program, some times all the child threads are getting executed complete even if the main thread exits.
In the 2 threads , i am processing some files. in testA thread A alone, 1 file alone is not getting processed some times. but many times, all the files are getting processed and i do not have any issues.
Java makes a distinction between a user thread and another type of thread known as a daemon thread. The difference between these two types of threads is that if the JVM determines that the only threads running in an application are daemon threads (i.e., there are no user threads), the Java runtime closes down the application. On the other hand, if at least one user thread is alive, the Java runtime won't terminate your application.
When your main() method initially receives control from the Java runtime, it executes in the context of a user thread. As long as the main-method thread or any other user thread remains alive, your application will continue to execute.
In your case, the threads are user threads and hence are allowed to complete before the main thread exits.
i am processing some files. in testA thread A alone, 1 file alone is
not getting processed some times. but many times
The reason for the above is could be something else than thread exits. It could be file locks, synchronization issue etc.
Thread (Java SE 10 & JDK 10):
When a Java Virtual Machine starts up, there is usually a single non-daemon thread (which typically calls the method named main of some designated class). The Java Virtual Machine continues to execute threads until either of the following occurs:
The exit method of class Runtime has been called and the security manager has permitted the exit operation to take place.
All threads that are not daemon threads have died, either by returning from the call to the run method or by throwing an exception that propagates beyond the run method.
The background threads will keep running, even if the MAIN thread completes.
If you want MAIN to stop them (example, when MAIN is complete), have your MAIN set a "keep running" flag variable (which you must set as "volatile"), which the threads occasionally look at. MAIN sets it to false (variable) or null (object) when MAIN wants to stop them. When it's false or null, then the thread must "return;".
This is somewhat complex to implement, there are many ways, but easiest is to make your Runnable an inner class, so that your Runnable has easy sharing of the flag.
For the best implementations, look up this technique in Java applets' start/stop routines.
Once the main thread exits, it takes the children with it. Perhaps by "finish" the second article simply means no more operation other than waiting for the children. Once the main thread calls System.exit(0); it's over -- every body dies.
Say you have two threads running: threadA and threadB. in the main method. The first code is the nice way of terminating the thread -- just one of many ways:
threadA.start();
threadB.start();
final long intercept = 300;
long startTime = System.currentTimeMillis();
while (threadA.isAlive() && mis.isAlive()) {
threadA.join(intercept);
if (System.currentTimeMillis() - startTime > intercept) {
threadB.interrupt();
threadA.interrupt();
threadA.join();
}
}
System.exit(0);
Below is an abrupt way of killing all threads from within main:
System.exit(0);

Question on Java Thread, output consistent

In the below code the answer is always Started 0 1 2 3 Complete. Im just wondering how it is possible.
If someone could help with the consistency of the output, it would be nice
public class TestOne extends Thread {
/**
* #param args
*/
public static void main(String[] args)throws Exception {
// TODO Auto-generated method stub
Thread t = new Thread(new TestOne());
t.start();
System.out.println("started");
t.join();
System.out.println("Complete");
}
public void run(){
for(int i=0;i<4;i++){
System.out.println(i);
}
}
Most likely you're getting the same results because, most of the time, the main thread starts a new thread then, before that new thread has a chance to print anything, the main thread prints its started message. The join in the main thread then forces it to wait until the other thread has finished, then it prints Complete.
You have a race condition here. The instant you start the second thread, it's indeterministic as to which order the lines will be output (other than the complete line which is made deterministic by virtue of the wait call, as previously mentioned).
But a race condition doesn't guarantee that you'll get different results on multiple runs, only that it is possible. You still shouldn't rely on that behaviour, of course.
For example, the following code:
public class TestOne extends Thread {
public static void main (String[] args) throws Exception {
Thread t = new Thread (new TestOne());
t.start();
Thread.sleep (1000); // <- Added this.
System.out.println ("Started");
t.join();
System.out.println ("Complete");
}
public void run() {
for (int i = 0; i < 4; i++) {
System.out.println (i);
}
}
}
will output:
0
1
2
3
Started
Complete
Although, even then, the order is not guaranteed as it may take more than a second for the thread to "warm up" - sleep is rarely a good solution to race conditions. I've just used it here for illustrative purposes.
When you say Thread t = new Thread(); nothing special happens because you are not creating a "Thread" per se. It is just an object that has the "characteristics" to become a thread of execution. For the object to be a "Thread" you have to call t.start(); and this is where the magic lies.
When you say t.start() the JVM creates a new stack for the newly created thread to run. It associates that stack to the thread object in question. And then makes it available for scheduling. Basically this means that it queues the thread in the JVM scheduler and in the next time slice it is also available for execution. The JVM actually does a lot more than this, my answer is just oversimplified for your example.
Invariably, meanwhile all these thread + stack creation, your main thread has the opportunity to move to its next instruction which in your case is System.out.println("started");.
Theoretically, what you say is true, "Started" could come anywhere in between 0, 1, 2, 3. However in reality, since your t.start() is an "expensive" method, it takes some time to complete, during which the main thread generally gets the chance to execute its next instruction.
If you want to know the details of t.start(); look into the Java source code.
Clearly, you are seeing a consistent result (and this particular result) because on your machine the call to the child thread's run method is consistently happening after the println in the main thread.
Why is it consistent?
Well, simply because your platform's native thread library is behaving in a consistent fashion!
Typical modern Java virtual machine implementations use the host operating system's native thread support to implement Java threads, and to perform Java thread scheduling. On your machine, the native thread implementation appears to be consistently allowing the current thread to return from the Thread.start() call immediately and keep executing.
However, it is not guaranteed that this will always happen. For instance, if the machine was heavily loaded and the main thread had just about exhausted its current timeslice, it could get descheduled during or immediately after the start call, allowing the new thread to run first.
Furthermore, on another platform the normal scheduler behaviour could be different. The scheduler could consistently cause the current thread to deschedule and let the new one go first. Or it could happen "randomly".
The JVM and Java library specs deliberately do not specify which thread "goes first" precisely to allow for differences in the thread implementation ... and variation due to differences in hardware, system load and so on.
Bottom line - the apparent consistency you are seeing is an "artifact", and you shouldn't rely on it, especially if you want your application to work on a wide range of JVMs.
Simply put, the scheduling of the started thread with respect to the main thread is JVM implementation dependent. But that being said, most implementations, if not all, will leave the starting thread running to the completion of its timeslice, until it blocks on something, or until it is preempted by a higher priority thread (if preemptive scheduling is being used, also JVM implementation dependent).
The Java spec just does not say very much which is very specific about threading, deliberately to grant JVM writers the most scope for their implementation.
t.join() means "block until thread t has finished", which explains the "Completed" being last.
EDIT: In answer to question re "Started"...
The call to Thread.start() means "please schedule this thread to run", and it will start when java feels like starting it. The chance of that happening between t.start() the println() is platform dependant, but small on systems I've used (thx to # Stephen C for platform info).
This code however outputs 0, Started, 1, 2, 3, Completed:
Thread t = new Thread(new TestOne());
t.start();
try
{
Thread.sleep(100); // Added sleep between t.start() and println()
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println("Started");
t.join();
System.out.println("Complete");
When you start a thread it takes time (nothing comes for free or occurs instantly)
The thread which is already running will almost always be quicker to print out than a thread which has just started.
If you really want to the order to be different every time you can use run() instead of start() This works because you only have one thread.

Categories

Resources