I'm trying to improve my JAVA. Now i have one questions i don't understand about threading.
My trying code is that,
public class MyThread implements Runnable {
private int end;
private String name;
public MyThread(String name, int end) {
this.end = end;
this.name = name;
}
#Override
public void run() {
for (int i = 0; i < end; i++) {
System.out.println(name + " : " + i);
}
}
}
public class ThreadLesson {
public static void main(String[] args) {
Thread thread1 = new Thread(new MyThread("thread1", 6));
Thread thread2 = new Thread(new MyThread("thread2", 5), "thread2");
thread1.start();
thread2.start();
}
}
On lesson output is
thread1 : 0
thread2 : 0
thread2 : 1
thread2 : 2
thread1 : 1
thread2 : 3
thread1 : 2
thread2 : 4
thread1 : 3
thread1 : 4
thread1 : 5
My outout is
Thread1:0
Thread2:0
Thread1:1
Thread1:2
Thread1:3
Thread1:4
Thread1:5
Thread2:1
Thread2:2
Thread2:3
Thread2:4
My Question is,
Why my out is not same lesson output ? There have some problem or who write that lesson just edit output for article to be beaty.
Somewhere in the lesson this might have been written in bold letters . You should not expect same results as shown here. You have started 2 threads by passing 2 different runnables. WIthout proper synchronization, there is no way of telling what the output would be.
Yes, you might find that very odd at the beginning that the values obtained vary greatly. In fact, there is no way to determine the proper output when two or more unsynchronized thread are allowed to run simultaneously.
This can be understood as
When threads are created they are said to be born state, you do not run a thread by using the run() but you use the start(). Now you may ask the reason behind the logic.
It is quite simple, if you use the run() then the processor must run the thread at that moment, which can cause problem. But if you use the start() then you tell the processor that you want to run the thread. Now after this the processor will take care of the thread as soon as it is free to do so.
It must be clear that the modern processors perform a number of task simultaneously. To achieve this, they can use either Round-Robin method or Preemptive scheduling to complete the task.
In time-slicing, each process is given same amount of processor time. Whereas in preemptive scheduling, the task with higher priority is given the preference.
Now when a number of threads run simultaneously then it depends on the operating system to allocate the processor to any thread. So any thread can get the processor which can change the output you see.
Now if the threads are synchronized then the conditions change and the program can have a fixed path.
We can not predict output pattern in this kind of cases as output will be solely depend upon jvm's Thread manager. If you want to have a predicted output you can go for Thread.sleep(timeinml) method as this will provide thread synchronization
Related
I would like to understand that does java actually run multiple threads in parallel in a multi core CPU, or there is context switching between threads and only one thread is active and others are waiting for their turn to run.
In other words, is there a possibility that 2 threads are running in parallel???
Because my Thread.currentThread() does not give me a array of threads, but only one thread which is running.
So what is the truth, does only one thread run at a time while others wait or multiple threads can run in parallel, if yes , then why my Thread.currentThread() method return only 1 thread object.
Edit : .....
I have created 2 classes to count numbers
1 class does it synchronously and the other one divides it into two halves and executes the two halves in 2 threads..(intel i5(4 CPUs), 8GB ram)
the code is as follows :
common class :
class Answer{
long ans = 0L;}
Multi Thread execution :
public class Sheet2 {
public static void main(String[] args) {
final Answer ans1 = new Answer();
final Answer ans2 = new Answer();
Thread t1 = new Thread(new Runnable() {
#Override
public void run() {
for(int i=0;i<=500000; i++) {
ans1.ans = ans1.ans + i;
}
}
});
Thread t2 = new Thread(new Runnable() {
#Override
public void run() {
for(int i=500001;i<=1000000; i++) {
ans2.ans = ans2.ans + i;
}
}
});
long l1 = System.currentTimeMillis();
try {
t1.start();t2.start();
t1.join();
t2.join();
long l2 = System.currentTimeMillis();
System.out.println("ans :" + (ans1.ans + ans2.ans) +" in "+(l2-l1) +" milliseconds");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Single Thread execution :
public class Sheet3 {
public static void main(String[] args) {
final Answer ans1 = new Answer();
long l1 = System.currentTimeMillis();
for(int i=0;i<=1000000; i++) {
ans1.ans = ans1.ans + i;
}
long l2 = System.currentTimeMillis();
System.out.println("ans :" + (ans1.ans ) +" in "+(l2-l1) +" milliseconds"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
}
My Single thread execution is faster than my multi threaded execution, I though the context switching was putting a overhead on the execution initially and hence the multithreaded execution output was slower, now I am having muti core CPU (4 CPU), but still single threaded execution is faster in this example..
Can you please explain the scenario here... is it because my other processes are eating up the other cores and hence my threads are not running in parallel and performing time slicing on the CPU ???
Kindly throw some light on this topic.
Thanks in advance.
Cheers.!!!
In short yes it does run on separate threads. You can test it by creating 100 threads and checking in your process explorer it will say 100 threads. Also you can do some computation in each thread and you will see your multicore processor go upto 100% usage.
Thread.currentThread gives you the current thread you are running from.
When you start your program you are running on the "main" thread.
As soon as you start a new thread
new Thread(myRunnable);
any code located in the myRunnable will run on the new thread while your current thread is is still on the main Thread.
If you check out the API http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html it gives allot more detailed description of the thread.
The actual threading mechanism can vary between CPU architectures. But the real problem is that you're misinterpreting the method name. Thread.currentThread() doesn't return the thread executing at the current moment in time; it returns the thread currently executing the method call, that is, itself.
Yes it does. Run any simple infinite loop on more than one threads and you'll see the cpu usage > 100% on a multi-core CPU.
Yes it does run threads concurrently .That is the very purpose of the multithreading concept .you may find the folowing discussion helpful :
Current Thread Method java
Not a complete answer here, just adding to what others already have said:
The Java Language Specification does not require that threads run in parallel, but it allows them to do so. What actually happens in any given Java Virtual Machine depends on how that JVM is implemented.
Any practical JVM will create one "native" (i.e., operating system) thread for each Java thread, and let the operating system take care of scheduling, locking, waiting, notifying,...
Recently I've seen some code which depends on order of execution in different threads which was achieved by calling Thread.sleep with some values. It worked without any problems but I'm sure that in some rare cases it would not. I wrote some code where order of output depends on how precisely Thread.sleep works.
public class Test {
public static Thread createDelayedPrintThread(final String text,
final long delay) {
return new Thread() {
public void run() {
try {
Thread.sleep(delay);
System.out.print(text);
} catch (InterruptedException e) {
}
}
};
}
public static void main(String[] args) {
Thread t1 = createDelayedPrintThread("t1", 10);
Thread t2 = createDelayedPrintThread("t2", 10);
t1.start();
t2.start();
}
}
This code obliviously can output booth t1t2 and t2t1 so I made delays different:
Thread t1 = createDelayedPrintThread("t1", 10);
Thread t2 = createDelayedPrintThread("t2", 20);
Now it outputs t1t2 but I still sometimes get t2t1. It usually happens when I do some CPU/IO intensive operations.
If I change delays to extremely big values
Thread t1 = createDelayedPrintThread("t1", 1_000); // one second
Thread t2 = createDelayedPrintThread("t2", 60_000); // one minute
would be there any guarantees that the application will output t1t2?
First, your understanding is correct; no amount of Thread.sleep() (and by the way, since Java 5 you should really be using TimeUnit instead, as in TimeUnit.SECONDS.sleep(2L)) will guarantee in-order execution; you cannot guarantee when the OS will schedule this or that thread.
would be there any guarantees that the application will output t1t2?
Yes.
For instance, a volatile boolean variable shared by those two threads will do (although you'll need to busy wait so this is not ideal). Another example is a Semaphore.
Solutions are many, and what you will end up with depends entirely upon your requirements.
Thread.sleep is not guarantees.
Java tutorial, about Thread.sleep():
"However, these sleep times are not guaranteed to be precise, because they are limited by the facilities provided by the underlying OS. Also, the sleep period can be terminated by interrupts, as we'll see in a later section. In any case, you cannot assume that invoking sleep will suspend the thread for precisely the time period specified."
So, you need add other multithreading logic for guarantees execution order.
I'm trying to start a thread in a for-loop. This task should only wait for a second (Thread.sleep()), so every time the loop starts over again, a new thread is started and it should cause the code after the thread to wait until it is executed.
public void count()
{
for(int i = 29; i>=0; i--)
{
Thread t1;
t1 = new Thread(new TimerClass());
t1.start();
String s = String.valueOf(i);
jLabel6.setText(s);
System.out.println(s);
}
}
public class TimerClass implements Runnable{
#Override
public void run()
{
try{
Thread.sleep(1000);
System.out.println("Timer");
} catch(InterruptedException e)
{
}
}
}
As you can see, I implemented in both methods System.out.println() to check if they are actually executed. I get this:
29
28
27
26
...//25 - 3
2
1
0
Timer
Timer
Timer
//in all 29 times Timer
So it should be 29, Timer, 28, Timer and so on, but it isn't.
Does anyone know what's wrong with the code?
Thanks a lot.
Your main loop that is starting the thread is likely dominating the CPU, so it finishes doing its entire loop and only then do the threads get a chance to go.
In fact, given that all of your threads sleep for an entire second and you're only looping 29 times, you're guaranteed that your loop will finish (and print all of the numbers) before your threads do. Add a sleep to your main loop if you want the threads to print - remember, the main loop doesn't stop when you start a thread.
You can join a thread to the main thread so first your thread will finished then main thread
public void count()
{
for(int i = 29; i>=0; i--)
{
Thread t1;
t1 = new Thread(new TimerClass());
t1.start();
t1.join();
String s = String.valueOf(i);
jLabel6.setText(s);
System.out.println(s);
}
}
Here is my code for spawning 2 threads or one thread depends on arrayList size but in my case this threads are doing much more complex tasks then just waiting 1 sec
for (int i = 0; i < array.size(); i += 2) {
Thread t1 = null;
Thread t2 = null;
if (i < array.size() - 1 && array.size() > 1) {
t1 = new Thread(array.get(i));
t2 = new Thread(array.get(i + 1));
t1.start();
t2.start();
}
else {
t2 = new Thread(array.get(i));
t2.start();
}
if (t1 != null)
t1.join();
if (t2 != null)
t2.join();
}
In my code I populate arrayList with Objects that Implements Runnable interface.
Even if you sleep the thread for 1ms, your results would be the same. If you can manage the thread to sleep for the time less than it takes to print the results, your result could be as expected. Here is my code where I have put the time of 1 ms but yet the results are the same.
public class MultiThreading implements Runnable
{
public void run()
{
try
{
Thread.sleep(1);
System.out.println("Timer");
}
catch(Exception e)
{
}
}
public static void main(String [] args)
{
for(int i = 29; i>=0; i--)
{
Thread t1;
t1 = new Thread(new MultiThreading());
t1.start();
String s = String.valueOf(i);
System.out.println(s);
}
}
}
If you comment out the Thread.sleep(1) method, then your results are as you expected.
Delay is much enough to let the for loop in count() to finish before is can print 'timer' from thread.
What is happening is that the thread you started starts executing and immediately goes to sleep. In the meantime, your loop just keeps running. As the whole point of threads is that they run asynchronously, I don't really understand why you think your main loop should be waiting for it to finish sleeping. The thread has started running and is now running independently of the main loop.
If you want to wait for the thread you just started to finish (in which case, you might as well use a method), then use one of the synchronisation primitives, i.e. Thread.wait().
What you actually want to do is block your main thread while another thread is running. Please don't use Thread#sleep statements, as these are unreliable in order to "make your application work". What you want to use instead is Thread#join. See dharr his code for an example.
Also, it's better to use Executors and ExecutorServices when creating threads or running async tasks.
Threads are interesting. Think of a virtual thread as a physical thread. There are many threads on the clothes you're wearing, all working at the same time to hold your shirt together. In virtual terms what Thread.start() does is start a thread on a different strand WHILE the following code continues to execute, (i.e. Two Threads work simultaneously like 2 runners run next to each other). Consider putting a break point right after Thread.start(). You'll understand.
For your desired effect, just put a Thread.sleep() in the main loop. This will cause an output of
29
Timer
28
Timer
// etc.
Hope this helped.
Jarod.
Another analogy to the threads in a shirt:
Think of threads as coworkers to your main programm (which is a thread itself). If you start a thread, you hand some work to this coworker. This coworker goes back to his office to work on this task. You also continue to do your task.
This is why the numbers will appear before the first thread/coworker will output anythig. You finished your task (handing out work to other coworkers) before he finished his.
If you want to give out some work and then wait for it to be finished, use t1.join() as suggested by others. But if you do this, it is senseless to create new Threads, because you don't (seem) to want to process something in parallel (with many coworkers) but in a specific order - you can just du it yourself.
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.
We have a scheduled task that runs every 10 seconds and a thread pool with 3 threads that actually update a static common map. Every 10 seconds the scheduled action prints this map.
The problem is that I want the scheduler to stop printing after the 3 threads finish with the map. But here is the key. I don't want to stop scheduler instantly, I want to print first ( the final version of the map) and then finishes.
public class myClass implements ThreadListener {
public static ArrayList<Pair<String, Integer>> wordOccurenceSet = new ArrayList<Pair<String, Integer>>();
int numberOfThreads = 0;
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
public void getAnswer(Collection<CharacterReader> characterReaders, Outputter outputter) {
ExecutorService executor = Executors.newFixedThreadPool(characterReaders.size());
OutputterWriteBatch scheduledThread = new OutputterWriteBatch(outputter,wordOccurenceSet);
scheduler.scheduleAtFixedRate(scheduledThread, 10, 10, TimeUnit.SECONDS);
for (CharacterReader characterReader : characterReaders) {
NotifyingRunnable runnable = new CharacterReaderTask(characterReader, wordOccurenceSet);
runnable.addListener(this);
executor.execute(runnable);
}
}
#Override
public void notifyRunnableComplete(Runnable runnable) {
numberOfThreads += 1;
if(numberOfThreads == 3 ){
//All threads finished... What can I do to terminate after one more run?
}
}
}
The Listener actually just get notified when a thread finishes.
First of all, make your numberOfThreads synchronized. You don't want it to become corrupted when two Reader threads finish concurrently. It's a primitive int so it may not be corruptable (i am not that proficient with JVM), but the general rules of thread safety should be followed anyway.
// 1. let finish OutputterWriteBatch if currently running
scheduler.shutdown();
// 2. will block and wait if OutputterWriteBatch was currently running
scheduler.awaitTermination(someReasonableTimeout);
// 3. one more shot.
scheduler.schedule(scheduledThread,0);
// You could also run it directly if your outputting logic in run()
// is published via separate method, but i don't know the API so i suppose
// only Runnable is published
But this shouldn't be called directly from notifyRunnableComplete, of course. The listener method is called from your Reader threads, so it would block the last one of 3 threads from finishing timely. Rather make a notification object which some other thread will wait() on (preferably the one which executed getAnswer()), notify() it when numberOfThreads reaches 3 and put the above code after the wait().
Oh, and when wait() unblocks, you should double check that numberOfThreads is really 3, if not, cycle back to wait(). Google "spurious wakeup" to explanation why this is needed.