I have four threads t1,t2,t3,t4 acting on same object of the class.I have some restriction,t2 should execute only after t1 has executed and t3 should execute only after t2 has executed,and same is the case with t4.I mean sequence should compulsarily be t1 then t2 then t3 then t4.How can we make sure that these four threads will execute in sequence only.
If you need to control the sequence like that, you don't have parallelism, and multithreading is useless. You seem to need only a single thread that will perform those operations sequentially.
trying using something known as a 'semaphore' .its basically a lock and key mechanism which will allow a single thread to run at a time provided they acquire a lock and release it when they are done.
example
Related
I have an integer in my Statistics.java class like this
int completionAmount = 0;
When the program startups I run a sql query in the main() method and set the completionAmount int based on what it returns (such as 10000).
After that's done I start a new single threaded executor that runs every 1 second and it uses that completionAmount integer to keep counting, do I need to synchornize the access to that integer now every time I use it in the new thread, because I loaded it from the main thread on startup, or since the main thread will no longer be using the integer, I won't have to make any changes?
Assuming you are doing something like this, in the same thread:
completionAmount = /* initialize from query; never set again */
new Thread(/* thing that uses completionAmount */).start();
then no, no additional synchronization is needed.
According to JLS 17.4.5:
A call to start() on a thread happens-before any actions in the started thread.
So, you've got a happens-before relationship between the write to completionAmount and its read.
Actually, you mention a single-threaded executor in the question. I'm assuming this is specifically an ExecutorService. From the Javadoc:
Actions in a thread prior to the submission of a Runnable or Callable task to an ExecutorService happen-before any actions taken by that task, which in turn happen-before the result is retrieved via Future.get().
So, provided the assignment happens before you submit the task to the executor, you've got a happens-before relationship, so no additional synchronization is required.
If "a single-threaded executor" you mention is a single-threaded ExecutorService,then synchronization is not needed.
Beacause single-threaded ExecutorService can ensure only one thread can access completionAmount integer on the same time,and the rest of your code must keep that.
Integer is not thread safe,you can use AtomicInteger instead of Integer to ensure thread safe.
I started to do research to find out why the word "join" is used for the Thread.join() method. In fact, it waits for the thread to end on which it is called and pauses the main thread to wait for it so, there is nothing to join. So, its name should be something like:
Thread.pauseCaller();
Thread.freezeCaller();
Thread.focusThread();
Thread.runBefore();
I found one simple sentence after too much research which says that:
Thread.join(); name comes from the concept of the calling thread waiting until the specified thread joins it.
I am totally unable to get this above sentence into my mind and failed to understand the background context of using the word join for this method. What does the word "join" represent in this context? There is nothing to join anything else; instead, it just pauses the calling thread to wait for the thread followed by the join(). So, can anyone tell the context of using the join word for this method?
The word "join" comes from the ForkâJoin model, where "fork" means to split the thread into multiple threads for parallel processing, and "join" means to wait for the parallel threads to complete their part, before continuing in a single thread.
Join is a common term used in models of concurrency, which implies that two separate independently running threads are synchronising with each other and one thread will not proceed until the other reaches a specific join point. So 2 threads are joining back together into one. In Java, this is usually when the other Thread finishes its task.
Note that this might not be exactly the same in models where the tasks are backed by reusable worker threads, such as when using an ExecutorService to wait for a result, and using CompletableFuture.join() to block until the result is available. In this case the joining is more related to the task executed in parallel than the actual underlying worker thread which might be reused for other tasks afterwards.
The name itself comes from the fork-join model for parallelizing tasks and collecting their results.
I have a question on multithreading.
Suppose I want to perform two actions simultneously like I want to add a friend record to a file and also display the friend record using concurrent threads at the same time.
I created a single thread which started and the display was taken care by it and in the main method which started the thread I performed the action of saving the record to file.
Do both of these processes occur simultaneously.
This is part of my code.
Runnable2 r2 = new Runnable2(L) ;
Thread t2 = new Thread(r2);
t2.start();
F.addElement(L);
oos1.writeObject(F);
There is no such thing as simultaneosuly. One will happen before the other, but, if you do not use explicit synchronization mechanisms, you cannot know which will be executed first (it depends on the OS, on hardware, on the JVM). It is very possible that if you run the program 100 times, 99 times event 1 will run before event 2, and the last time it happens the other way around, and you get one of those bugs that are so difficult to reproduce.
You really should not count on the order and you should use synchronization mechanisms when using multi-threading.
I know that Thread and Task are in different abstraction-level.But anyway,I'm still confused that what's the relationship of them.And,by the way,I think that the Task tells how to do a job and the Thread actually excute the job according to a Task instance.Is my understanding correct?thank u^
I assume by Task you mean Runnable and Callable. The relationship is simple:
Thread might be used to execute multiple tasks
might - because you don't need a separate thread to execute tasks (well, technically, everything runs inside a thread - you don't need a separate one)
multiple - thread can be reused; it can run multiple tasks from a collection like queue
Typically one thread executes one Runnable passed to Thread constructor or multiple Callables passed to ExecutorService (wrapping thread pool in most cases).
If by Task you mean something like this, then the difference is that the task is used to run some thread-like code execution, but has additional properties, such as when to run it, how many times, and the option to cancel its execution, whereas a thread will just go ahead and run once immediately.
A task is rather abstract it can be implemented as a process or a thread.
Your understanding is correct.
We can do the analogy with workflow patterns where tasks are something that needs to be done in a process and threads are resources used to process or execute them.
I have 2 threads T1 and T2 ,both have different jobs so usually we prefer to accomplish this task by thread Joins.
But we can do this with out using join(). We can add T2 thread's code inside T1 thread.
What difference does this make ?
Joining a thread means that one waits for the other to end, so that you can safely access its result or continue after both have finished their jobs.
Example: if you start a new thread in the main thread and both do some work, you'd join the main thread on the newly created one, causing the main thread to wait for the second thread to finish. Thus you can do some work in parallel until you reach the join.
If you split a job into two parts which are executed by different threads you may get a performance improvement, if
the threads can run independently, i.e. if they don't rely on each other's data, otherwise you'd have to synchronize which costs performance
the JVM is able to execute multiple threads in parallel, i.e. you have a hyperthreading/multicore machine and the JVM utilizes that
usually we prefer to accomplish this task by thread Joins.
No we don't. We accomplish this task by starting two threads. There is no obligation to use join() so there is no 'should' about it. If you want to pause the current thread while another thread completes, do so. If you don't, don't.
If you call T1.join(); from T2 it will wait for T1 to die (finish). It is a form of thread synchronization, but from what you describe you can simply fire of two thread and simply do not use join. If you use two threads then the work will be done in parallel, if you put the code only in one thread then the work will be done sequentially.
Here is the reason to use join: You use it when final result depends on result of two tasks which could run at the same time.
Example1:
After user clicks submit button the program has to call two external webservices to update their respective systems. It can be done at the same time that is why we would create a separate thread for one of webservices.
The user will sit before the screen and wait for a notification: Your submission is OK! The screen should say OK only after both threads finished.
Two things.
Join is used only when one thread must wait for the open to finish (lets say thread A prepares a file and thread B cannot continue until the file is ready). There are instance where threads are independent and no join is needed (for example most of daemon threads).
With threading you get several things:
- mainly, independence in the order of execution. Lets say that you have a program that when you push a button does some heavy processing. If you do that processing in the main thread, you GUI will freeze until the task is finished. If you do the processing in another thread, then the GUI thread is "freed" and the GUI keeps working.
- in some (most) of modern computers, creating several threads could allow the OS to use the different cores to serve different threads, improving performance.
The drawback is bigger complexity, as you need information of other threads execution state.
You could use something like a java.util.concurrent.CountDownLatch, eg:
CountDownLatch doneSignal = new CountDownLatch(2);
and have each thread countDown() when they're done, so a main thread knows when both threads have completed.
using Join also like we can add the T2 thread's code inside T1 thread
join() like the method name implies waits for the thread to die and joins it at the end of execution. You can add one thread's code inside another but that would destroy the purpose of using 2 separate threads to run your jobs concurrently. Placing one code after the other would run your statements in sequence. There is no concurrency.
When in doubt, consult the javadocs - http://download.oracle.com/javase/1.5.0/docs/api/java/lang/Thread.html#join%28%29
If T1 and T2 do different tasks which do not depend on state changes caused by each other - you should not join them to reap advantages of parallel execution. In case there are state dependenices you should synchronize both threads using mechanisms like wait/notify or even .Join() depending on your use case.
And as for, combining the run() methods of both threads, it's entirely left to you. I mean, you should understand why both threads are of different "types" (as they have different run() body) in the first place . It's a design aspect and not a performance aspect.
All the parallel threads typically needs to join at some point in the code thereby allowing them to wait until all threads terminate. After this point typically the serial processing continues. This ensures proper synchronisation between peer threads so that subsequent serial code does not begin abruptly before all parallel threads complete the collective activity.
The main difference is when we join T2 thread with T1 ,the time T2 is executing the job can be utilised by T1 also ,that means they will do different job parllely.But this cann't happen when you include the T2 thread code inside T1 thread.