1) What is Thread and how it is
different from process
Threading means doing more than one thing at a time. Threads
execute code inparallel of each other threads currently running. When you’ve only one
processor, there is a thread running at the same time of the others, you only
have the impression of concurrency.
When you’ve multiple processors, you’ll see the power of
multithreading. In this case, you can have your threads distributed on the
processors of the computer.
Running eclipse, ms-word , visual studio at same time is the
multiple process this is not the multiple thread and IPC that is inter process
communication is also not the thread.
2) When we have being using threads as
the main thread then.
·
We
can efficiently make use of process. Like when one thread is waiting for
something other thread let execute it means like if 1 program is waiting for
something means it’s not busy and let other go to execute so multiple flow of
control for a task.
·
Make
use of multi core processors [Like our PC]
·
lives and dies on the heap
3)
Thread of execution is an individual process (a
"lightweight" process) that has its own call stack. In Java, there is
one thread per call stack
4)
Inter process communication allow us to manage thread execution...
when to run what thread, how to give up the processor or control to another
thread.
5) Suspend, sleep, wait, blocked thread
from I/O request i.e. input output are way to give control to other thread.
6)
So for I/O
attribute providing , Sleep time interval,
notify, notify all are way to resume thread execution
7)
We don’t call run() method directly because then it will
not threat it as thread, It will run as part of main thread.
8)
For thread scheduling Java use algorithm base on operating
system. Like Microsoft use round robin
and Linux use priority preemption so priority set on window has no impact.
9) There's only one CPU on most of the
machines running Java. What gives? The JVM, which gets its turn at the CPU by
whatever scheduling mechanism the underlying OS uses, operates like a mini-OS
schedules its own threads regardless of the underlying operating system.
10)
The thread scheduler is the part of the JVM
(although most JVMs map Java threads
Directly to native threads on the underlying OS) that decides which
thread should
Run at any given moment, and also takes threads out of the run state.
11)
Daemon threads
background threads. We can create our own daemon thread by calling
setDaemon(true).
12)
Daemon thread will
keep running till all the user thread are alive, Then JVM kill the Daemon thread
automatically when no user thread found.
public class
ThreadDaemon Demo{
public static void
main(String[] args){
try{
Daemon d = new
Daemon (20);
User u = new
User(10);
d.start();
u.start();
}catch(Exception
e){
e.printStackTrace();
}
System.out.println("Exiting
main");
return;
}
}
class Daemon extends Thread{
private int iCount = 0;
Daemon (int
count){
iCount =
count;
setDaemon(true);
}
public void
run(){
try{
for(int i =
0; i < iCount; i++){
System.out.println("Daemon :: " + i);
Thread.sleep(1000);
}
}catch(Exception
e){
e.printStackTrace();
}
}
}
class User extends
Thread{
private int iCount = 0;
User(int
count){
iCount =
count;
}
public void
run(){
try{
for(int i =
0; i < iCount; i++){
System.out.println("User
:: " + i);
Thread.sleep(1000);
}
}catch(Exception
e){
e.printStackTrace();
}
}
}
|
13) When to use the Daemon thread.
Example: Consider you
have a web service that you wish to offer to your consumers without any
user-interaction by way of essentially user-threads form the primary use-case
for setting a user thread as a daemon so this service runs till all user thread
exits.
As a consequence, until user-threads exist JVM guarantees that
daemon threads run continuously. You can find examples like GC, UI Thread etc.
those are daemons.
14) User thread won’t die even after main thread dies
15) When you use join on particular thread, meaning that
thread is saying “Wait till I finished”.
The other thread will wait till this thread finish. But this all depends on
which thread acquired the lock first.
public class
JoinThreadDemo implements Runnable {
int value = 0;
public static void
main(String[] args) throws InterruptedException {
// TODO
Auto-generated method stub
JoinThreadDemo
obj1 = new JoinThreadDemo();
obj1.setValue(10);
Thread
t1 = new Thread(obj1);
t1.setName("KING
- THREAD");
t1.start();
t1.join();
Thread
t2 = new Thread(obj1);
t2.setName("Subject
Thread");
t2.start();
System.out.println("I
am " + Thread.currentThread().getName() +"
End here");
}
public int
getValue() {
return value;
}
public void
setValue(int value) {
this.value =
value;
}
@Override
public void run()
{
// TODO
Auto-generated method stub
for(int i=0
;i< value;i++){
System.out.println("Thread
Running " + Thread.currentThread().getName() + "--" + i);
}
}
}
|
16) join(long millis) /join(long millis,
int nanos) Waits at most milliseconds
for this thread to die/ Waits at most millis milliseconds plus nanos
nanoseconds for this thread to die.
17) Two threads have same priority and keep running so both never give up (starvation). So yield means leave running state now and other thread get a chance.
public class
ThreadYieldDemo implements Runnable {
Thread t;
ThreadYieldDemo(String str) {
t = new Thread(this,
str);
// this will call run()
function
t.setPriority(10);
t.start();
}
public void run()
{
for (int i =
0; i < 5; i++) {
// yields control to
another thread every 5 iterations
if ((i %
5) == 0) {
/* causes the
currently executing thread object to temporarily
pause and allow other threads
to execute */
if(Thread.currentThread().getName().equals("ThreadOne")){
System.out.println(Thread.currentThread().getName()
+ " yielding
control...");
Thread.yield();
}
}
}
System.out.println(Thread.currentThread().getName()
+ " has finished
executing.");
}
public static void
main(String[] args) {
new
ThreadYieldDemo("ThreadOne");
new
ThreadYieldDemo("ThreadTwo");
new
ThreadYieldDemo("ThreadThree");
}
}
|
18) In practice, what yield() is supposed to do is
make the currently running thread head back to runnable to allow other threads
of the same priority to get their turn. So the intention is to use yield() to
promote graceful turn-taking among equal-priority threads. In reality, though,
the yield() method isn't guaranteed to
do what it claims, and even if yield() does cause a thread to step out of
running and back to runnable, there's no guarantee the yielding thread won't
just be chosen again over all the others! So while yield() might—and often does—make a
running thread give up its slot to another runnable thread of the same priority, there's
no guarantee. A yield() won't ever cause a thread to go to the
waiting/sleeping/ blocking state. At most, a yield () will cause a thread to go
from running to runnable, but again, it might have no effect at all
19) sleep() allows the thread to go to sleep state
for x milliseconds. When a thread goes into sleep state it doesn’t release the
lock.
20)
wait() allows thread to release the lock and
goes to suspended state. The thread is only active when a notify() or
notifAll() method is called for the same object.
21) Once a
thread acquires a lock in some object, it may call any other synchronized
method of that same object using the lock that it already holds.
22) As
static methods are class methods and have only one copy of static data for the
class, only one lock for the entire class is required. Every class in java is
represented by java.lang.Class instance. The lock on this instance is used to
synchronize the static methods.
23)
List the
methods which when called the thread does not release the locks held?
Following are the methods.
·
notify()
·
join()
·
sleep()
·
yield()
24) List the
methods which when called on the object the thread releases the locks held on
that object?
wait()
25) Interleaving
is managed by the processor and describe the possible situations of several
threads executing some statements
26) In Java,
to make operation atomic the first way to make that is to use a lock. All Java
objects contains an intrinsic locks, we’ll use that lock to make methods or
statement atomic. When a thread has a lock, no other thread can acquire it and
must wait for the first thread to release the lock.
27) As
static methods are class methods and have only one copy of static data for the
class, only one lock for the entire class is required. Every class in java is
represented by java.lang.Class instance. The lock on this instance is used to
synchronize the static methods.
28) As the
thread executing the static synchronized method holds a lock on the class and
the thread executing the non-satic synchronized method holds the lock on the
object on which the method has been called, these two locks are different and
these threads do not block each other.
29) To
acquire the lock, you have to use the synchronized keyword to automatically
acquire and release a lock for a code. You can add the synchronized keyword to
a method to acquire the lock before invoking the method and release it after
the method execution.
30) If you
have two methods with the synchronized keyword, only one method of the two will
be executed at the same time because the same lock is used for the two methods.
Check ShowTwoSyncMethodDemo.jave for code
class
TwoSyncMethod{
public synchronized void
MethodOne() throws InterruptedException{
for(int i=0 ;
i < 10 ;i++){
System.out.println("method
1 running by Thread = " +
Thread.currentThread().getName());
Thread.sleep(2000);
}
}
public synchronized void
MethodTwo() throws InterruptedException{
for(int i=0 ;
i < 10 ;i++){
System.out.println("method
2 running by thread = " + Thread.currentThread().getName());
Thread.sleep(2000);
}
}
}
class
ShowTwoSyncMethodDemo1 extends Thread{
TwoSyncMethod obj = null;
public
ShowTwoSyncMethodDemo1(TwoSyncMethod obj){
this.obj =
obj;
}
public void
run(){
try {
//obj.MethodOne();
obj.MethodTwo();
}
catch (InterruptedException e) {
// TODO
Auto-generated catch block
e.printStackTrace();
}
}
}
class
ShowTwoSyncMethodDemo2 extends Thread{
TwoSyncMethod obj = null;
public
ShowTwoSyncMethodDemo2(TwoSyncMethod obj){
this.obj =
obj;
}
public void
run(){
try {
obj.MethodOne();
}
catch (InterruptedException e) {
// TODO
Auto-generated catch block
e.printStackTrace();
}
}
}
public class
ShowTwoSyncMethodDemo {
public static void
main(String[] args) {
TwoSyncMethod
obj = new TwoSyncMethod();
ShowTwoSyncMethodDemo1
demo1 = new ShowTwoSyncMethodDemo1(obj);
ShowTwoSyncMethodDemo2
demo2 = new ShowTwoSyncMethodDemo2(obj);
demo2.start();
demo1.start();
}
}
|