Docsity

Programming Java Part4-Java Programming-Lecture Slides, Slides of Java Programming

Partial preview of the text

Download Programming Java Part4-Java Programming-Lecture Slides and more Slides Java Programming in PDF only on Docsity!

Life Cycle of Thread

106

new

ready

start()

running

stop() dead

dispatch

completion

wait()

waiting

sleeping

blocked

notify()

sleep()

Block on I/O

I/O completed

Time expired/

interrupted

suspend()

suspend()

A Program with Three Java Threads  Write a program that creates 3 threads 107

class C extends Thread{public void run(){for(int k=1;k<=5;k++){System.out.println("\t From ThreadC: k= "+k);}System.out.println("Exit from C");}}class ThreadTest{public static void main(String args[]){new A().start();new B().start();new C().start();}} 109

 [raj@mundroo] threads [1:76] java ThreadTest

Exit from B

Thread Priority

 In Java, each thread is assigned priority, which

affects the order in which it is scheduled for running.

The threads so far had same default priority

(NORM_PRIORITY) and they are served using FCFS

policy.

 Java allows users to change priority:

 ThreadName.setPriority(intNumber)

 MIN_PRIORITY = 1

 NORM_PRIORITY=

 MAX_PRIORITY=

112

Thread Priority Example

class A extends Thread { public void run() { System.out.println("Thread A started"); for(int i=1;i<=4;i++) { System.out.println("\t From ThreadA: i= "+i); } System.out.println("Exit from A"); } } class B extends Thread{ public void run() { System.out.println("Thread B started"); for(int j=1;j<=4;j++) { System.out.println("\t From ThreadB: j= "+j); } System.out.println("Exit from B"); } } 113

Thread Priority Example

threadC.setPriority(Thread.MAX_PRIORITY); threadB.setPriority(threadA.getPriority()+1); threadA.setPriority(Thread.MIN_PRIORITY); System.out.println("Started Thread A"); threadA.start(); System.out.println("Started Thread B"); threadB.start(); System.out.println("Started Thread C"); threadC.start(); System.out.println("End of main thread"); } }

adrish.b@ardentcollaboratio

115 docsity.com

Accessing Shared Resources

 Applications Access to Shared Resources need to be

coordinated.

 Printer (two person jobs cannot be printed at the same time)

 Simultaneous operations on your bank account.

 Can the following operations be done at the same time on

the same account?

 Deposit()  Withdraw()  Enquire() 116

Shared Resources

 If one thread tries to read the data and other thread

tries to update the same data, it leads to inconsistent

state.

 This can be prevented by synchronising access to the

data.

 Use ―Synchronized‖ method:

 public synchronized void update()

 …

118

the driver: 3 rd Threads sharing the same object 119 class InternetBankingSystem { public static void main(String [] args ) { Account accountObject = new Account (); Thread t1 = new Thread(new MyThread( accountObject )); Thread t2 = new Thread(new YourThread( accountObject )); Thread t3 = new Thread(new HerThread( accountObject )); t1.start(); t2.start(); t3.start(); // DO some other operation } // end main() }

Monitor (shared object access): serializes operation on shared object class Account { // the 'monitor' int balance;

// if 'synchronized' is removed, the outcome is unpredictable

public synchronized void deposit( ) {

// METHOD BODY : balance += deposit_amount;

public synchronized void withdraw( ) {

// METHOD BODY: balance -= deposit_amount;

public synchronized void enquire( ) {

// METHOD BODY: display balance.

} 121

Multithreaded Server

122 Server Threads Message Passing Facility Server Process Client Process Client Process

User Mode

Kernel Mode

Multithreaded Server

String Handling

Introduction:

. As is the case in most other programming languages, in Java a string is a sequence of characters.

But, unlike many other languages that implement strings as character arrays, Java implements

strings as objects of type String

When you create a String object, you are creating a string that cannot be changed. That is, once

a String object has been created, you cannot change the characters that comprise that string. At

first, this may seem to be a serious restriction.

However, such is not the case. You can still perform all types of string operations. The difference is

that each time you need an altered version of an existing string, a new String object is created

that contains the modifications. The original string is left unchanged. This approach is used because

fixed, immutable strings can be implemented more efficiently than changeable ones. For those

cases in which a modifiable string is desired, there are two companion class to String called

StringBuffer and StringBuilder, whose objects contain strings that can be modified after they

are created.

String , StringBuilder and StringBuffer classes are defined in java.lang. Thus, they are

available to all programs automatically. All are declared final, which means that neither of

these classes may be sub classed.

String , StringBuffer,StringBuilder implement the CharSequence interface.

http://www.ardentcollaboration

124 docsity.com

String Constructors

The String class supports several constructors. To create an empty String, you call the default constructor. For example, String s=new String(); will create an instance of String with no characters in it. The String class provides a variety of constructors to handle this. To create a String initialized by an array of characters, use the constructor shown here: String(char chars[ ]) Here is an example: char chars[] = { 'a', 'b', 'c' }; String s = new String(chars); This constructor initializes s with the string “abc”. 6/24/

http://www.ardentcollaboration

125 docsity.com