Você está na página 1de 33

 Multithreading in java is a process of

executing multiple threads simultaneously.

 Thread is basically a lightweight sub-process,


a smallest unit of processing.

 Multiprocessing and multithreading, both are


used to achieve multitasking.

arjun.rokaya@gmail.com 2
 we use multithreading than multiprocessing
because threads share a common memory
area.

 They don't allocate separate memory area so


saves memory, and context-switching between
the threads takes less time than process.

 Java Multithreading is mostly used in games,


animation etc.

arjun.rokaya@gmail.com 3
 A process runs independently and isolated of
other processes. It cannot directly access shared
data in other processes. The resources of the
process, e.g. memory and CPU time, are allocated
to it via the operating system.

 A thread is a so called lightweight process. It has


its own call stack, but can access shared data of
other threads in the same process. Every thread
has its own memory cache. If a thread reads
shared data it stores this data in its own memory
cache. A thread can re-read the shared data.

arjun.rokaya@gmail.com 4
 It doesn't block the user because threads are
independent and you can perform multiple
operations at same time.

 You can perform many operations together


so it saves time.

 Threads are independent so it doesn't affect


other threads if exception occur in a single
thread.

arjun.rokaya@gmail.com 5
 A thread is a lightweight sub process, a
smallest unit of processing. It is a separate
path of execution.

 Threads are independent, if there occurs


exception in one thread, it doesn't affect
other threads. It shares a common memory
area.

arjun.rokaya@gmail.com 6
arjun.rokaya@gmail.com 7
 A thread can be in one of the five states.

 The life cycle of the thread in java is


controlled by JVM. The java thread states are
as follows:

◦ New
◦ Runnable
◦ Running
◦ Non-Runnable (Blocked)
◦ Terminated

arjun.rokaya@gmail.com 8
arjun.rokaya@gmail.com 9
 There are two ways to create a thread:

1. By extending Thread class


2. By implementing Runnable interface.

arjun.rokaya@gmail.com 10
 Thread class provide constructors and
methods to create and perform operations on
a thread.

 Thread class extends Object class and


implements Runnable interface.

arjun.rokaya@gmail.com 11
Thread()
Thread(String name)
Thread(Runnable r)
Thread(Runnable r,String name)

arjun.rokaya@gmail.com 12
1. public void run(): is used to perform action for a thread.
2. public void start(): starts the execution of the thread.JVM calls the
run() method on the thread.
3. public void sleep(long miliseconds): Causes the currently executing
thread to sleep (temporarily cease execution) for the specified
number of milliseconds.
4. public void join(): waits for a thread to die.
5. public void join(long miliseconds): waits for a thread to die for the
specified miliseconds.
6. public int getPriority(): returns the priority of the thread.
7. public int setPriority(int priority): changes the priority of the thread.
8. public String getName(): returns the name of the thread.
9. public void setName(String name): changes the name of the thread.

arjun.rokaya@gmail.com 13
 The Runnable interface should be
implemented by any class whose instances are
intended to be executed by a thread.

 Runnable interface have only one method


named run().

 public void run(): is used to perform action


for a thread.

arjun.rokaya@gmail.com 14
 start() method of Thread class is used to start a
newly created thread.

 It performs following tasks:


◦ A new thread starts.
◦ The thread moves from New state to the Runnable state.
◦ When the thread gets a chance to execute, its target run()
method will run.

arjun.rokaya@gmail.com 15
arjun.rokaya@gmail.com 16
arjun.rokaya@gmail.com 17
arjun.rokaya@gmail.com 18
 Thread scheduler in java is the part of the JVM
that decides which thread should run.

 There is no guarantee that which runnable thread


will be chosen to run by the thread scheduler.

 Only one thread at a time can run in a single


process.

 The thread scheduler mainly uses preemptive or


time slicing scheduling to schedule the threads.

arjun.rokaya@gmail.com 19
 Default priority of a thread is 5
(NORM_PRIORITY).

 The value of MIN_PRIORITY is 1 and the value


of MAX_PRIORITY is 10.

 thread.setPriority( Thread.MAX_PRIORITY );
 Thread.currentThread( ).getPriority( )

arjun.rokaya@gmail.com 20
arjun.rokaya@gmail.com 21
 The sleep() method of Thread class is used to
sleep a thread for the specified amount of
time.

◦ public static void sleep(long miliseconds)throws


InterruptedException

Thread.sleep(500); will halt thread for 500 milli second.

arjun.rokaya@gmail.com 22
class TestSleepMethod1 extends Thread{
public void run(){
for(int i=1;i<5;i++){
try{Thread.sleep(500);}catch(InterruptedException e){System.o
ut.println(e);}
System.out.println(i);
}
}
public static void main(String args[]){
TestSleepMethod1 t1=new TestSleepMethod1();
TestSleepMethod1 t2=new TestSleepMethod1();

t1.start();
t2.start();
}
}

arjun.rokaya@gmail.com 23
 The join() method waits for a thread to die.

 In other words, it causes the currently


running threads to stop executing until the
thread it joins with completes its task.

 Example: Calculate tan(x) = sin(x)/cos(x)


 Where six and cosx value calculation should
be completed before we calculate tanx

arjun.rokaya@gmail.com 24
arjun.rokaya@gmail.com 25
arjun.rokaya@gmail.com 26
 The shutdown hook can be used to perform
cleanup resource or save the state when JVM
shuts down normally or abruptly.

 Performing clean resource means closing log


file, sending some alerts or something else.

 So if you want to execute some code before


JVM shuts down, use shutdown hook.

arjun.rokaya@gmail.com 27
 The JVM shuts down when:

user presses ctrl+c on the command prompt


System.exit(int) method is invoked
user logoff
user shutdown .

arjun.rokaya@gmail.com 28
arjun.rokaya@gmail.com 29
 Synchronization in java is the capability to
control the access of multiple threads to any
shared resource.

 Java Synchronization is better option where


we want to allow only one thread to access
the shared resource.

arjun.rokaya@gmail.com 30
 When you have two threads that are reading
and writing to the same 'resource', say a
variable named foo, you need to ensure that
these threads access the variable in an atomic
way. Without the synchronized keyword, your
thread 1 may not see the change thread 2
made to foo, or worse, it may only be half
changed. This would not be what you
logically expect.

arjun.rokaya@gmail.com 31
arjun.rokaya@gmail.com 32
arjun.rokaya@gmail.com 33

Você também pode gostar