Core Java Notes

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 360

Cere

Java
Netes

K.Naveen Kumas
GECM-R5
8096633784
o Multi Thae ading :
pro cess : Any appli cation which is unden execution'on núnning is called
process.
thre ad: IH is the smallest unit of a procesS ond it is also called as light e
weight process.
ha pn0cess we may have multiple openotions to be penfonmed and
ton handling each and eveny openation we will have athead.
50 hene eveny pnocegs we may have multiple theads based on num
ben of openations in a
procesS3.
NotePad VLC Media
’one thnead audio ti
t1 video

i Multi-Tasking: subtitlest3
The process of penfon ming
the process is executing multiple taske at atime,
called multi-tasking.
We have two types of
Opnoce9s based multitasking:
OThnead based multitasking.
O Process based ulti-tasking
multi- tasking :
’ f we pesifonm multi-tasking bå using procegs is
called pnocess
based multi-tasking
- In process based multi-tasking the context
suwitching will take
much time becauge it has to swap both stacks and
memogof a
process between heap area and execution anea.
Thnead bosed multi-tasking:
-’f we penfonm multitasking bå using threa ds then it is called
multi- thae ading on thaead based multi-tasking.
he cont ext switching between thneads will take less time uwhen
Compamed to processes be cause hene we have to swap only the
Stacks of thneod between heap anea and execution anea and noneed
t0 swap memony becouse fon all the theads it contains,a single
memony called shaned memo ny.'osido bose o e Dc
Ihis,shaned memory is containing all the nesouhces ohich ane
Nequined foniall thnead and these nesoun ces one:shaned among
all the threads based on the nequinements.
,Note:
Multithneading is betten than: multipnocessi ng becouse multithaeading
, takes less time when
companed to multi--pro cessing to complete thein
execution.
oCneating of Thae ads :
We can cneate thne ads in two
ways:
By extending Thnead class.
By implementing nunnable bov ortoie ilá
intenface.
cloen.nie)reioom
By extending Thaeod class:
UDg wa-ii tbsnAle
public class MyThnead extends Thnead {
public void nuno{
fon (int i=1: i<=10: i++{
aontn S.o.pln("Run"); i+oinM")ola o.2

public static void main(Sting(]


angs){
Mylhnead t1 = new MyThnead (O:
ti. sleep:
fon( int 0=1: i<=10; i ++)f
S.opln("Main"); .3viteA

Note :
Wheneven we create a thead we must and should ovenide nun)
method.
We hove to wite the statements 0n logics which you have executed
stanto
by a thead. Inonden to execute athnead we have to call
method by cheating thaead object. This stant(o method intennally calls
nunc) method whene the, actual execution of thaead i9stanting.
We cannot decide the onden of execution of multiple thneads.
D By implementing Runnable intenface:
Ez::
class; Myhneadi implements Runnable{
public void nun(){
fon( int i=1; i<=10: i++){
S.o,plnc"Run'ti):
public static void main(Stning] angs)i
MyThneadi t1= new
MyThneod1(O;
Thae od t new Thnead (t1);
t.stant ();
fon(int i=1; i<= 10; 0++){
S.o.pln("Main"+i):

oLife cycle of Thne ad:


’ New state
’Active. ’ Runnable state

SRunning state
Waiting /Blockedstate
’ Terminated Dead state.
New
stant
Active
Runnable) Running

ezecution stop)
completes
Tenminated/
suspendo/sleept)
(nesUme)
Dead waiting
ONew state
me:
’Wheneven we cneate a thread then it is autom atically pesent in
New state.
Active st ate:
’rom New state the thnead.is moved' into active state by calling the
stant() method.
’ Ih active stote we have
two states:
. Runnable state.
" Running state.
"Runnable state: Aften enteziing ioto active state if the
waiting foa cpu time thnead is
slot. then we can say it is Runnable
Running state : rf the cpu time slot is state.
we can say it is tunning
alloted to the thnead. then
state. In nunning stote the
in unden execution. thread.ill be
Waiting on blocked state:
’ If a thne ad got any
inte1uptton Iike
method etc,those kind of methods-wtllsuspendomethod
on sleepc)
move the thnead from
Iunning state to waiting | blocked stote.
’ In wat ting state the thnead is not
stops its ezecution.
terminated but ittemponanily
’ Fnom waiting state to the thread again moves to nunnable state
once the waiting 19 comple tada
(y Tenminate/ Dead state:
’F the thread execution i9 completed then it moves to tenm inate/
Dead state.
’If we call the stop) method fo a thneàd then alsoit moveg to
tenmingte/ dead state.
oMethods of Thead clasS:. 1
"set Prionity()
"stant() get Id()
"stopc) Suspend
"getName) 1egUme(
set Name() " yieldc
"getPrionity() "sleep(time ms)
"getstate()
"stopc :
’It is used to terminate the execution of athnead completely.
getNamec)::
’ It is used to netun the name of oa thnead.
" set Name():
’ It is used to set a new name to a thnead ifyou dont want to
use the default name provided, by the ystem.
" get Prionity o:
t is used to netunn the paionity of a thnead 0s a integer
value.
" set Prionity():
’ It is used to set a pnionity fon a thread.
We have pionities in the nonge from'i to io.Thnead class provid.
es thre constant paioni ties which ane static membens and to
acess thege piertes membensyou have to call them by ustng
thnead class. Those paion1ties ane
*. MIN-PRIORITY1
* NORM.PRIO RITY -5
* MAX- PRIORITY 10
’ Fon eveny tha ead by default it contains NORM- PRIORITY.
"getIdco::
It is used to netunn the id of a thread which is intennally pa
ded by the system.
SUSpend():
Wheneve1 we call suspendofon athne ad. the thneod stops it executior
temponaily ond it is going to enten into waiting state.
" 1egume:

Wheneven we call nesumeC) it nestants the execution of suspended


thaead.
yieldo method:.
Wheneven we call yseldomethod .it stops its execution temponanily
and providing tts time slot fon all othen nema ining thneads and
It nestants its execution once all the thneads complete thejn ex
ecution.
sleep():
Wheneven we call sleepc) method foi a thie ad, then the thread
is moving to waiting state and it aestants tts exeeution once
the given time is completed.
" getstate ():
getstate() methÍd netuNns the cuNNent state ofa thread.
Ex:
public class Usenf
public static void main(Stningt] angf thiows Inteninupted Excep
tionf
Thaeat ti new Thnead):
Thmead2 ta= new Thread2 ():
S.o.pln(t1.get
t1.stantc):
stote(0):
t1.suspend():
t.stontc):
t1. stopc):
t2.stop):
S.o.pln (t1.get Name (0):
So,pln(t2. getName()):
t1.setNome (" KNK");
S.opln(t1.getNome()):
ti.yie ldc:
S.opln (t1.getstate(j:
tt.sleep(so000);
S.opln(t1get
ti. set
Paioaity0);
Prionity( Thaead.MAX-PRIORITY);
So.pln (t1.getPaionity):
S.o.pln( IhieodIo:"+ t1.get Id()):
S.o.pln (Thaead..ID:"+ t2.getIdO):
t1,nesUmecT;
S.apln(t1.getstate (0):
oSynchnoni zation:

Wheneven we ne ezecuting multiple thneads at atime thene is a
possi bility that we may get Dead Lock situation.
’Dead Lock situation is nothing but wheneven multiple
to access the resounces from shaned
thheods tntes
memóy then thene is a possib
lity fsom that these nesounces will be
shaned among all the thneads
and then these thne ads ane waiting fon
then
eztna nes0uN ces which ane
hold by each othen and no thnead is going to
’ hen these thneads will be
complete Its execution,
infinite yaiting state and this intinite
waiting state is called de ad lock.
’lo ove ncome this deadlock situation we
ane using Synchroni
zation,
Ln synchnoni zation only one thaead
’In th nead can access the iesOuNce9 at a
time mean wbile the othen th neads has to be in waiting state until
1st thaead comple tes its erecution.
infinite waiting thnéads thet n
t2 without
ti Synchnonization t1 t2 1egvied nesOUNces
RI R1 R2
R2& R4 R2 R3
R3 R4

-aftei synchnonization

R4
R1 R2 R3 R4S
shaned memony
ti on ly one thread
R1 R2 Can acce ss the
R2 R3 AeSO0ces at à time
R3 R4

Ex:
Opublic class Counten{
public void paintValues(int n){
fon(int i=1; i<= 10, i++)B
S.o.pln(n++):

public class T1 eztends Thaeadf


Counten C:
T1( Countencof
this.c =C:
public void nunof
C. pnint Values (1):

() public closs T2 extends Thneadf


Counten C:
T2 (COunten c)f
this.c =C:

public void nuncf


c. phint Values (io1):

u Without synchnonnzation
public class CountenTest{
:

public static void main


(Stning[ angs)
Counte c= new
Counten():
T1 t1= new T1();
T2 t2 = new
T2();
t1.stot():
t2. stanto:

o/p:
2
3

6
101
102
103
104
105
106
10+
108
109
110

,0 With synchaonization:
public class Countenf
public synchnonized void paint Values (int nf
for (int i=1: i<=10: i++)i
4

So.pln(n++):

O/p:
1

102
103
10+
105
106
107
108
109
110
Synchoni zed key wond:
To applu synchnonization fon any me thod o a block of fnstaucti ons
we ane going to use a key w0rd called synch nonized.
oProgramming on Anunays :
a.Waite a java prnogram to find whethe the sum of adjacentelements
of given Q4Nay is a palindnome on not.
input aNNay5,3,8,6,2 ,9,4}
output aNNAy =8. 22,33}
public cloass SumOfNumOf Anaysf
publte static void main (Stning C] angs
int A[]={5,3,6.6.2,9, 4}:
int sum= A[O]:
fon(int i=1:i< A.length: i++)f
Sum = SUM +ALI];
if(1s Palindaome (sum)){
S.o.pl6um+" ");

paivate static boolean isfalindnome (int


int nuM= S0m3 sumn)f
int ev =03
while(sum! =o)
int iem= suM%.10;
NeV= nev% 10+ ems
SUM = SUM/10;

if( num z= nev)


netunn tyue:
netuan false:

o/p 22 33
consecutive elemente
. Wnite a java pnogom to find the sum of
pnesent in fibona cci senies 0n not
OT an annay is
input aNNay = { 2,3.8.4. 4:6,}
output anNay = {5.13,21, 34}
public class Sumof Consecutive Ele{
public static void main (Staing[] angs)f
int AC) ={2,3,8, 4.4.6,4:
int sum = A[O]:
fon(int i=1: i< A.length: i++){
SUm =SUm+ A[[]:
if (isFibonacci(sum)i
5.0.p (SUm+" "):

pnivate static boolean sFibona cci(int sum){


int a=o, b=1;
int nes =0;
while (a+b)< = Sum){
a = b;
b=neS;
ifCsum==o l| Sum==1 || eg ==sUm
netun su true;

netuan false:

5 13 21 34
a. Wnite a java prognam to insent a new element into given QnNay
at a specific position and pint the nesultant annou.
public class InsentNewEle Into Annau{
publie ease static void main (Stning[J angs)f
int ALJ ={1,2, 3. 4}:
int ele 8:
int pos =2;
int B[J= new int [A. length +1]:
fon( int i= o.j=0 ; i<B.length. L++)f
ifc i==pos- 1)X
BIiJ = ele:

elsef
8Ci] = A[j++]:

fon( int i:6){


S.o.p(i+" "):

O/p:
1 8 2 3 4

You might also like