Java - Count in COUNTDOWNLATCH - java

While running each thread why does the countdown.getCount() always print '3' even after the previous thread has already called countdown.countDown() and reduced the Latch Count by 1?
I am kind of worndering how Java knows that the Latch Count has reached 0, so that it can release all the 3 threads.
import java.util.concurrent.CountDownLatch;
class b {
static final CountDownLatch countdown = new CountDownLatch(3);
public static void main(String[] args) {
for (int i = 0; i < 3; ++i) {
Thread t = new Thread() {
public void run() {
System.out.printf("Starting on %d other threads.\n",
countdown.getCount());
countdown.countDown();
System.out.printf("new on %d other threads.\n",
countdown.getCount());
try {
countdown.await(); // waits until everyone reaches this
// point
// System.out.println("Go again : "
// +countdown.getCount());
} catch (Exception e) {
}
}
};
t.start();
}
System.out.println("Go");
}
}

you are starting 3 threads in parallel. depending on how fast they start, they could all print "3" before any of the threads manages to call countDown() (at least for the "Starting on..." line). the "new on ..." line, however, should print out some range of numbers between 2 and 0.

It's absolutely possible that all three threads print "Starting on 3.." as the threads run in parallel, and the count doesn't change until a thread executed countDown(). To really understand what's going on, I suggest you prepend System.nanoTime() and thread name before your print statements as below:
...
Thread t = new Thread("Thread-" + i) {
...
System.out.printf("%d> %s: Starting on %d other threads.\n", System.nanoTime(), getName(), countdown.getCount());
countdown.countDown();
System.out.printf("%d> %s: new on %d other threads.\n", System.nanoTime(), getName(), countdown.getCount());
Sometimes you'd get an output like below which may give you the impression that Thread-2 is disregarding Thread-1's call to countDown:
1407489646569321000> Thread-0: Starting on 3 other threads.
1407489646569324000> Thread-1: Starting on 3 other threads.
1407489646602463000> Thread-1: new on 1 other threads.
1407489646569513000> Thread-2: Starting on 3 other threads.
1407489646602107000> Thread-0: new on 2 other threads.
1407489646603275000> Thread-2: new on 0 other threads.
However, that is not the case, and we can verify the correct order of operations by looking at the timestamp. The mixup in the output is due to inherent unpredictability in thread scheduling, depending on which thread gets the cpu splice.
Having said that, they may not always print 3, depending on thread scheduling or delays. As an example, try putting a Thread.sleep(..) as shown below:
public static void main(String[] args) throws Exception {
for (int i = 0; i < 3; ++i) {
Thread t = new Thread() {
public void run() {
/* As before */
}
};
t.start();
Thread.sleep(100); // Artificial Delay
}
}
Now you should see different results like below:!
1407490223575404000> Thread-0: Starting on 3 other threads.
1407490223607879000> Thread-0: new on 2 other threads.
1407490223676233000> Thread-1: Starting on 2 other threads.
1407490223676818000> Thread-1: new on 1 other threads.
1407490223777623000> Thread-2: Starting on 1 other threads.
1407490223778221000> Thread-2: new on 0 other threads.
Internally, the CountDownLatch maintains a first in, first out wait Queue (See. AbstractQueuedSynchronizer). The value of the count is synchronized, and the waiting threads are only released when the count becomes 0 or someother thread interrupts the waiting thread. This is the mechanism used by the latch to keep track of when all the threads have arrived at the latch.
If you're interested in understanding the latch in the context of testing, checkout http://razshahriar.com/2014/08/testing-asynchronous-code-in-java-with-countdownlatch/
Hope this helps clarify your investigation of the Program behaviour.

Related

I'm trying to run threads whose run() method has for loop, some loops are being skipped only when sleep() is used.Can anybody please explain why?

I'm trying to run four threads. run() method has a for loop that loops 10 times.In each loop the shared resource "x" is increment by 1. When all threads die, the for loop should have run 4x10 =40 times and x value should equal 40.
That is not happening in all runs of the my code.Each time I run the code it prints a different value of x.Most of the output values of x range from 33 to 40.
Why is it not 40 in every run? Does that mean some for loop loops are being skipped? Is it caused due being blocked?
NOTE : this does not happen when sleep() is removed. It prints 40 every single time.
My code :
public class MyThreadImplementsRunnable implements Runnable{
int x =0;
public void run() {
for(int i=0;i<10;i++){
x = x+1;
try {
Thread.sleep(1);
} catch (InterruptedException e) {
System.out.println("exception");
e.printStackTrace();
}
}
}
public static void main(String[] args) {
MyThreadImplementsRunnable m = new MyThreadImplementsRunnable();
Thread t1 = new Thread(m,"first");
Thread t2= new Thread(m,"second");
Thread t3= new Thread(m,"third");
Thread t4= new Thread(m,"fourth");
t1.start();
t2.start();
t3.start();
t4.start();
//To make sure not to go the next statement unless all threads die
while(t1.isAlive()|| t2.isAlive()|| t3.isAlive()||t4.isAlive()){
}
//After all threads die
System.out.println("now all threads are dead");
//value of the shared resource x after all threads exit
System.out.println(m.x);
}
}
Some test runs gave the following results :
Output:
now all threads are dead
34
Output:
now all threads are dead
33
x = x + 1 loads the value of x from memory, adds 1 to it and then stores it in x. Lets say Thread t1 loads 30 and at the same time thread t2 loads 30 they both increment 30 by 1 and store 31 in x instead of 32.
Why it's always 40 without sleep can be caused by many things I hypothesize that it's caused by each of the threads running very quickly and finishing before the next one starts.
You also don't use volatile and there are visibility issues but for now lets not get into that. This is also something you need to learn if you want to write multi-threaded code.
You are using a shared resource(x) between threads which is bound to create many problems like data race, visibility.. Your answer will be always different
#oleg I don't think Volatile will help in this scenario

i want to test java multithread ,but only one thread run

public class ThreadText
{
public static void main(String[] args)
{
windows w=new windows();
Thread t1=new Thread(w);
Thread t2=new Thread(w);
Thread t3=new Thread(w);
Thread t4=new Thread(w);/*four threads*/
t1.start();
t2.start();
t3.start();
t4.start();
}
}
i want to use four windows to sale 1000 tickets
class windows implements Runnable
{
int tickets=1000;
public void run()
{
synchronized(this)
{
while(tickets>0)
{
System.out.println(Thread.currentThread().getName()+" is saling"+tickets);
tickets--;
}
}/*i think problem is here*/
}
}
when i don't use synchronized ,all threads run,but results are wrong.
some tickets number are same.the correct result is that every window gets different ticket number.
Thanks
When you synchronize the entire loop, the first thread will get the lock and will count down to 0. The other 3 threads will wait until first thread releases the lock, at which point there's nothing left for them to do. In effect, the result is single-threaded.
To work correctly, you need to synchronize inside the loop, so the other threads can work too.
However, the first thread may still be too fast, so that it ends up doing all the work. To better simulate what you want, add a delay outside the synchronize block (making a sale takes time, you know). Added minimum delay of 1ms in the code below.
And finally, Java naming convention is for class names to start with an Uppercase letter, so it should be named Windows.
class Windows implements Runnable {
private int tickets = 1000;
#Override
public void run() {
String threadName = Thread.currentThread().getName();
for (;;) { // loop forever
synchronized (this){
if (this.tickets == 0)
break;
System.out.println(threadName + " is saling " + this.tickets);
this.tickets--;
}
try {
Thread.sleep(1);
} catch (InterruptedException e) {
break;
}
}
}
}
OUTPUT
Thread-0 is saling 1000
Thread-2 is saling 999
Thread-3 is saling 998
Thread-1 is saling 997
Thread-0 is saling 996
Thread-1 is saling 995
Thread-2 is saling 994
Thread-3 is saling 993
Thread-0 is saling 992
Thread-1 is saling 991
Thread-3 is saling 990
Thread-2 is saling 989
. . .
Thread-2 is saling 11
Thread-1 is saling 10
Thread-0 is saling 9
Thread-3 is saling 8
Thread-0 is saling 7
Thread-1 is saling 6
Thread-2 is saling 5
Thread-1 is saling 4
Thread-0 is saling 3
Thread-3 is saling 2
Thread-2 is saling 1
You do need to synchronize due to the tickets member being accessed by multiple threads. But because you are basing the run method on while tickets > 0, only 1 thread will ever run until the end. One solution would be to tie the execution of the thread to another variable and have the run method just decrement tickets once, then sleep so other threads can have a chance to run. For example, if you refactor your windows class as follows, then it will do what I think you want it to do.
class windows implements Runnable {
volatile boolean finished = false;
int tickets = 1000;
public void run() {
while(!finished) {
synchronized(this) {
if (tickets > 0) {
System.out.println(Thread.currentThread().getName()+" is selling " + tickets);
tickets--;
if (tickets <= 0) {
finished = true;
}
}
}
try {
Thread.sleep(10);
}
catch(InterruptedException ex) {
}
}
}
}
What you are experiencing is known as a race condition. That means due to the order of threads operating, you can get two threads thinking they decremented something but only one did, etc.
To address this, you have two options:
synchronized -- which is pretty heavy handed, and unless you put it at the smallest critical section is going to be too much.
AtomicInteger -- which makes sure that the integer is incremented or decremented safely across threads.
To fix your example and still use synchronized, your code should look like this:
class windows implements Runnable
{
int tickets=1000;
public void run()
{
while(tickets>0)
{
synchronized(this)
{
System.out.println(Thread.currentThread().getName()+" is saling"+tickets);
tickets--;
}
}
}
}
Of course, the down side to that is you have to remember to synchronize all access to the variable.
Using AtomicInteger the process is much easier to control:
class windows implements Runnable
{
AtomicInteger tickets = new AtomicInteger(1000);
public void run()
{
while(tickets.get() > 0)
{
System.out.println(Thread.currentThread().getName()
+ " is saling" + tickets.decrementAndGet());
}
}
}
From your code I understand that you are trying to replicate a Sales Window in Real Life for the Tickets.
Analogy (Look at the Image Link at the bottom of answer):
A place for sales of Tickets (Say, concert Tickets). This place has multiple Sections/Windows from where the exchange of money happens and the concert ticket is provided. Behind the Window there is a person that actually takes the money and gives u the ticket. Since in your example there is nothing related to money, so this is just a one sided exchange. Basically the person behind the window gives the ticket when ever a customer comes (Customer coming is like thread getting executed in your example).
There are only limited finite number of Ticket, each having a unique ticket number between 1 to 1000.
Your code has same instance of Runnable Window. And this same instance is provided for execution to all threads (All different Instances of Thread).
So your Real Life Design becomes like :
That the same person will give you the tickets from Window 1, 2, 3 etc. But at one time only one window can be taken care by this person.
So making your code effectively to run as Single Processer/Core code but poorer performance than the sequential code as the thread switching (if occurred) will have more overheads.
Now lets say we had multiple sales person - One for each window. Then the question becomes of NOT selling the same ticket by different sales person (Race Condition).
For this all the sales person have to take a ticket from a box one at a time. I.E. the part of getting the ticket is the only part that needs to be synchronized. This would be best achieved by Atomic Integers. Other answers have more than required chunk of code with in their synchronized blocks. This part has been answered (as per me) by #Berin Loritsch reply.
class TicketSeller /* Not windows*/ implements Runnable {
AtomicInteger tickets = new AtomicInteger(1000);
public void run() {
while (tickets.get() > 0) {
System.out.println(Thread.currentThread().getName()
+ " is saling" + tickets.decrementAndGet());
}
}
}
public class ThreadText {
public static void main(String[] args) {
Thread t1 = new Thread(new TicketSeller());
Thread t2 = new Thread(new TicketSeller());
Thread t3 = new Thread(new TicketSeller());
Thread t4 = new Thread(new TicketSeller());
/*four threads, four windows from where the ticket can be provided by 4
different TicketSellers*/
t1.start();
t2.start();
t3.start();
t4.start();
}
}
With this when a different thread comes into execution or multiple threads run in parallel the thread is not put to unnecessary sleep (And sleep doesn't even confirm avoiding of the race condition, by the way) and is blocked from execution for only a limited area of the code, i.e. tickets.get().
Of course you can go a few steps ahead an optimize this even more. But that would require a lot more deeper understanding and complex thinking. E.g. Sales person is allocated a certain number of tickets. And ticket shuffling happens so that to optimize that maximum number of tickets are sold in quickest execution time by something managing the tickets that each SalePerson has.
Ticket Sale Window Example :
https://www.google.com/imgres?imgurl=https%3A%2F%2Fimage.shutterstock.com%2Fimage-photo%2Fthree-windows-stadium-ticket-offices-260nw-1776188525.jpg&imgrefurl=https%3A%2F%2Fwww.shutterstock.com%2Fsearch%2Ftickets%2Bwindow&tbnid=BW8bA0aSqJTxaM&vet=12ahUKEwiVvvrmp47zAhU6g0sFHW8TCekQMygEegUIARC9AQ..i&docid=QQwLjL01dRWDoM&w=390&h=280&q=Ticket%20Sale%20Window&ved=2ahUKEwiVvvrmp47zAhU6g0sFHW8TCekQMygEegUIARC9AQ

Multithreading start method

and this a normal thread program
class Counter implements Runnable {
private int currentValue;
public Counter() { currentValue = 0; }
public int getValue() { return currentValue; }
public void run() { // (1) Thread entry point
try {
while (currentValue < 5) {
System.out.println(Thread.currentThread().getName() + ": " + (currentValue++)); // (2) Print thread name.
Thread.sleep(250); // (3) Current thread sleeps.
}
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + " interrupted.");
}
System.out.println("Exit from thread: " + Thread.currentThread().getName());
}
}
//_______________________________________________________________________________
public class Client {
public static void main(String[] args) {
Counter counterA = new Counter(); // (4) Create a counter.
Thread worker = new Thread(counterA, "Counter A");// (5) Create a new thread.
System.out.println(worker);
worker.start(); // (6) Start the thread.
try {
int val;
do {
val = counterA.getValue(); // (7) Access the counter value.
System.out.println("Counter value read by " + Thread.currentThread().getName()+ ": " + val); // (8) Print thread name.
Thread.sleep(1000); // (9) Current thread sleeps.
} while (val < 5);
} catch (InterruptedException e) {
System.out.println("The main thread is interrupted.");
}
System.out.println("Exit from main() method.");
}
}
and the output is
Thread[Counter A,5,main]
Counter value read by main thread: 0
Counter A: 0
Counter A: 1
Counter A: 2
Counter A: 3
Counter value read by main thread: 4
Counter A: 4
Exit from thread: Counter A
Counter value read by main thread: 5
Exit from main() method.
My question is even though the worker thread was started initially before the Main thread enters it's try block, Main thread execution starts first and then when the Main thread goes to sleep child thread gets into action.
As this picture(taken from "A Programmer's Guide To Java SCJP Certification : A Comprehensive Primer 3rd Edition"
Author: Khalid A Mughal, Rolf W Rasmussen) depicts that when the start method is called on the thread it returns immediately.
Please explain this point that why on invoking start method it return immediately and does the thread get starts on calling the start method. As here on calling the start method it doesn't invoke run method of the class. So when does actually the thread starts ?
Also explain this " the call to the start() method is asynchronous."
there are three things that you are missing in your overall analysis.
Call to thread's start method is sequential not parallel. Its the call to run method of Thread that is concurrent. So if you have 5 statements in main method that call start, the 5ht is not going t be called first. Thats the 'happens before' guarantee that JVM specs give you. However the run method of 1 first may get called before or after the call to the second start statement. This depends as its more of a CPU time slicing issue rather than program execution.
When more than 1 thread runs in your program the order of output is in-deterministic. That's because they run in parallel. You can never be sure that the same program will run in same order on two machines or even in two runs on the same machine. In your question you have posted only 1 output. Run the program like 20 times one after another and match the output. I am sure 2 or 3 would be entirely different.
Finally, you are basing your analysis on the order or execution of your concurrent code. That's the biggest blooper programmer make. Concurrent programs are never intended to run in a specific order or sequence. Just try to make your Runnable work an atomic mutually exclusive task (mutually exclusive to the rest of program or even to other Runnables) and track its own execution. Dont mix Threads together.
You cannot directly enforce which Thread is executed/running when. Once you start it, it's handled on lower level(usually by OS) and the results may differ on different machine or even in different execution. If you need more control, you need to use some synchronization mechanism.
The thread is isn't started synchronously underneath the call to start(). It happens later (asynchronously). In other words, just because you called start() doesn't mean the thread has started.
They why and how are all implementation details, that may depend on JVM and/or OS implementations.

when does the main thread die?

The question was to generate random numbers between 1 and 99 using a thread. However the problem here is I don't know where does the "main thread is stopping" coming from?
Doesn't the main thread die in the end?
This is the sample output:
Main thread stopping
Random no = 57
Random no = 47
Random no = 96
Random no = 25
Random no = 74
Random no = 15
Random no = 46
Random no = 90
Random no = 52
Random no = 97
Thread that generates random nos is stopping
Mythread class:
public class MyThread extends Thread {
MyThread() {
// default constructor
}
MyThread(String threadName) {
super(threadName); // Initialize thread.
start();
}
public void run() {
// System.out.println(Thread.currentThread().getName());
Random rand = new Random();
int newValue;
for (int i = 0; i < 10; i++) {
newValue = rand.nextInt(99);// generates any vale between 1 to 99
System.out.println("Random no = " + newValue);
}
System.out.println("Thread that generates random nos is stopping");
}
}
Main class:
public class HW5ex2a {
public static void main(String[] args) throws InterruptedException {
MyThread t = new MyThread();
t.start();
t.join();// wait for the thread t to die
System.out.println("Main thread stopping");
}
}
You can't rely on the order that main thread and other threads write to System.out.
Your thread t executes fine, the main thread waits for it to finish and then the main thread exits, all as expected. But this isn't reflected in the order that you see on System.out.
To directly answer your question - the main thread waits for the thread to finish, then it writes a message to System.out, then it dies. The only confusing thing is that, because you are writing to System.out from two different threads, you don't have any guarantees about the relative ordering. Println's from the two different threads could show up interleaved in any way...it just happens to show up with the output from the main thread first.
As Alexis Leclerc points out - you get an unpredictable interleaving, the same as in this java threads tutorial.
Memory Synchronization in a Multi-core System
Since both threads are being run on separate cores (most probably), the objects that the threads have access to are cached by each core (in L1 cache) for improved performance.
Whenever the state of the object is changed, all caches try to synchronize with value in RAM, which is not guarantied to occur immediately.
Some threads might be able to synchronize before other threads even if it violates happens-before relationship between them.
The reason behind this lies in the implementation of the java memory model.
The same thing is happening with System.out object here.
You can not guaranty the order in which the data is passed and flushed through it.
Therefore it is unpredictable. Calling
System.out.flush();
might improve the result, but it will not guaranty.
For more, refer to Multiple threads using System.out.println in Java
Hope this helps.
The main thread exit on below situation :-
Normally when program execution complete .
If you are using System.exit(1).
JVM crashes.
Hope it will help you.

Java multithreading - thread priority

Can anybody explain how thread priority works in java. The confusion here is if java does'nt guarantee the implementation of the Thread according to its priority then why is this setpriority() function used for.
My code is as follows :
public class ThreadSynchronization implements Runnable{
public synchronized void run() {
System.out.println("Starting Implementation of Thread "+Thread.currentThread().getName());
for(int i=0;i<10;i++)
{
System.out.println("Thread "+Thread.currentThread().getName()+" value : "+i);
}
System.out.println("Ending Implementation of Thread "+Thread.currentThread().getName());
}
public static void main(String[] args) {
System.out.println("Program starts...");
ThreadSynchronization th1 = new ThreadSynchronization();
Thread t1 = new Thread(th1);
t1.setPriority(1);
synchronized(t1)
{
t1.start();
}
ThreadSynchronization th2 = new ThreadSynchronization();
Thread t2 = new Thread(th2);
t2.setPriority(9);
synchronized (t2) {
t2.start();
}
System.out.println("Program ends...");
}
}
In the above program even if I change the priority I find no difference in the output.
Also a real time application of how thread priority can be used would be of great help.
Thanks.
Thread priority is just a hint to OS task scheduler and is dependent on the underlying OS. OS will try to allocate more resources to a high priority thread but it does not guarantee it. So if your program is dependent on thread priorities than you are in-turn binding your program to underlying OS, which is bad.
From Java Concurrency in Practice:
Avoid the temptation to use thread priorities, since they increase
platform dependence and can cause liveness problems. Most concurrent
applications can use the default priority for all threads.
Thread priority is only a hint to OS task scheduler. Task scheduler will only try to allocate more resources to a thread with higher priority, however there are no explicit guarantees.
In fact, it is not only relevant to Java or JVM. Most non-real time OS use thread priorities (managed or unmanaged) only in a suggestive manner.
Also very important, Priorties are different to every underlying plattform. Therefore you kind of loose your plattform freedom of java. See this summary as well:
Indeed, some priority levels can map to the same "native" priority level. Here's the list (based on the Hotspot code in OpenJDK 6):
Solaris
1 ⇒ 0
2 ⇒ 32
3 ⇒ 64
4 ⇒ 96
5 – 10 ⇒ 127
Of note is that on Solaris, you can't raise the thread priority above normal, only lower it: the priority value for 5 is the same as any of the higher values.
Linux
1 – 10 ⇒ 4 – -5 (nice values)
Of note is that on Linux, different thread priorities in Java do map to distinct priority values at native level.
Windows
1 – 2 ⇒ THREAD_PRIORITY_LOWEST
3 – 4 ⇒ THREAD_PRIORITY_BELOW_NORMAL
5 – 6 ⇒ THREAD_PRIORITY_NORMAL
7 – 8 ⇒ THREAD_PRIORITY_ABOVE_NORMAL
9 – 10 ⇒ THREAD_PRIORITY_HIGHEST
I've developed a lot of multi threaded java applications, and in my opinion if you have to set thead priorities you have another problem. Like a bad algorythm that consumes to much cpu time etc.... I always suggest to not change the java thread prio, since you can't rely on it anyways. (of course there are some scenarios where it makes sense)
There are several situations where setting a priority for a Thread is useful, you just must not start believing in any guarantees that come form such settings, as always: the order of execution with threads is undefined. If you think that your thread will be done earlier if you give it a higher priority, please read the statement above again until that's out of your head. ;)
You should define the priority based on how important it is for this thread to gain execution time compared to the others. Even though the underlaying system guarantees nothing, it still can provide a benefit for those JVMs that support it.
Example: You have a program that does some heavy calculation based on user input in your JFrame. It is a good practice to set those background threads to a low priority, because it is more important that the JFrame is responsive than working on the calculation (which will take a long time to finish anyways, a few more millis won't hurt). The OS will still assign most CPU time to the low priority threads, unless something more important needs it. But then it is good that this more important stuff gets the priority.
Now it could happen that on some systems the priority setting is ignored and the JFrame is again unresponsive, but then this does nothing worse to your code then not setting the priority to low in the first place.
The size of the tasks is too small and probably will complete right after the start. Also, if you have "enough" CPU cores, each worker thread will be allocated to one core, so the result will be the same.
Try the experiment in a different context, first increase the task size (for example by looping one thousand times to one million, without print) then increase the number of threads to exceed the number of cores you have and third, create your threads first and then start all the threads (you cannot start them at once, you will still need to loop through them).
In my case, I have chosen 10 threads because I ran the code on a processor with two hyper-threaded cores, running four simultaneous threads.
My changes to your example:
public class ThreadPriority implements Runnable {
public synchronized void run() {
System.out.println("Starting Implementation of Thread " + Thread.currentThread().getName());
float s = 0;
for (int i = 0; i < 1000; i++)
for (int k = 0; k < 1000000; k++)
s += k;
System.out.println("Ending Implementation of Thread " + Thread.currentThread().getName() + " " + s);
}
Thread t;
public ThreadPriority(String name, int prio) {
t = new Thread(this);
t.setName(name);
t.setPriority(prio);
}
public void start() {
synchronized (t) {
t.start();
}
}
public static void main(String[] args) {
System.out.println("Program starts...");
ThreadPriority[] th = new ThreadPriority[10];
for (int i = 0; i < th.length; i++) {
th[i] = new ThreadPriority("T" + i, i / 2 + 1);
}
for (ThreadPriority tp : th)
tp.start();
System.out.println("Program ending, wait for all the threads to complete");
}
}
Results are:
Program starts...
Starting Implementation of Thread T0
Starting Implementation of Thread T9
Starting Implementation of Thread T8
Starting Implementation of Thread T5
Program ending, wait for all the threads to complete
Starting Implementation of Thread T4
Starting Implementation of Thread T6
Starting Implementation of Thread T7
Starting Implementation of Thread T2
Starting Implementation of Thread T3
Starting Implementation of Thread T1
Ending Implementation of Thread T6 1.7592186E13
Ending Implementation of Thread T7 1.7592186E13
Ending Implementation of Thread T4 1.7592186E13
Ending Implementation of Thread T8 1.7592186E13
Ending Implementation of Thread T9 1.7592186E13
Ending Implementation of Thread T5 1.7592186E13
Ending Implementation of Thread T2 1.7592186E13
Ending Implementation of Thread T0 1.7592186E13
Ending Implementation of Thread T1 1.7592186E13
Ending Implementation of Thread T3 1.7592186E13
As you can see, the low number threads tend to end later, because the high number threads have higher priority. By turning the scale upside down:
for (int i = 0; i < th.length; i++) {
th[i] = new ThreadPriority("T" + i, 9 - i / 2 );
}
The low number threads complete faster than the high ones. Some threads complete even before other threads are started, because they have higher priority compared to the calling program:
Program starts...
Starting Implementation of Thread T0
Starting Implementation of Thread T1
Starting Implementation of Thread T2
Starting Implementation of Thread T3
Program ending, wait for all the threads to complete
Ending Implementation of Thread T2 1.7592186E13
Ending Implementation of Thread T3 1.7592186E13
Ending Implementation of Thread T0 1.7592186E13
Ending Implementation of Thread T1 1.7592186E13
Starting Implementation of Thread T9
Starting Implementation of Thread T4
Starting Implementation of Thread T8
Starting Implementation of Thread T7
Starting Implementation of Thread T5
Starting Implementation of Thread T6
Ending Implementation of Thread T4 1.7592186E13
Ending Implementation of Thread T5 1.7592186E13
Ending Implementation of Thread T7 1.7592186E13
Ending Implementation of Thread T8 1.7592186E13
Ending Implementation of Thread T9 1.7592186E13
Ending Implementation of Thread T6 1.7592186E13
Hope it helps!
package priority;
public class ThreadPriorityApp {
// Note : Thread priority may not be supported in some OS due to underlying task scheduler at OS level
/**
* MyThread is an inner class implementing Thread functionality
*
*/
class MyThread extends Thread {
public MyThread(String threadName) {
super(threadName);
}
public void run() {
System.out.println("Running thread - " + Thread.currentThread().getName());
}
}
public static void main(String[] args) {
//If priority is not set then main priority is set to threads created inside main thread - Parent to child
// Main thread priority - 5, is set to Thread 1 and Thread 2, if not manually assigned (commenting Line #34 and #35)
System.out.println("Main thread priority - " + Thread.currentThread().getPriority());
ThreadPriorityApp threadPriorityApp = new ThreadPriorityApp();
//We are creating two threads
MyThread th = threadPriorityApp.new MyThread("Thread 1");
MyThread th2 = threadPriorityApp.new MyThread("Thread 2");
// Range 1 to 10 - 10 being given as MAX Priority
th.setPriority(Thread.MIN_PRIORITY);
th2.setPriority(Thread.MAX_PRIORITY);
//We have started Thread 1 first and then Thread 2 later
th.start();
th2.start();
// Possible Outcomes(1) (With Priority - Line #34 and #35) :
// Running thread - Thread 2
// Running thread - Thread 1
// Possible Outputs(2) : (Without Priority - commenting Line #34 and #35)
// (1) Running thread - Thread 1
// Running thread - Thread 2
// OR
// (2) Running thread - Thread 2
// Running thread - Thread 1
}
//Happy coding -- Parthasarathy S
}
//The iterative and recursive with memorize both shows count as 1424 for digits of length ten starting with 1.
int[][] b = {{4,6},{6,8},{7,9},{4,8},{0,3,9},{},{1,7,0},{2,6},{1,3},{2,4}};
public int countIterative(int digit, int length) {
int[][] matrix = new int[length][10];
for(int dig =0; dig <=9; dig++){
matrix[0][dig] = 1;
}
for(int len = 1; len < length; len++){
for(int dig =0; dig <=9; dig++){
int sum = 0;
for(int i : b[dig]){
sum += matrix[len-1][i];
}
matrix[len][dig] = sum;
}
}
return matrix[length-1][digit];
}
public int count(int index, int length, int[][] matrix ){
int sum = 0;
if(matrix[length-1][index] > 0){
return matrix[length-1][index];
}
if( length == 1){
return 1;
}
for(int i: b[index] ) {
sum += count(i, length-1,matrix);
}
matrix[length-1][index] = sum;
return sum;
}

Categories

Resources