Java Threads
Java Threads
Java Threads
JavaThreads
class MyThreadDemo {
public static void main(String args[]) {
MyThread t1 = new MyThread(1);
MyThread t2 = new MyThread(2);
MyThread t3 = new MyThread(3);
t1.start();
t2.start();
t3.start();
System.out.print("Main ends");
}
}
Basic Threads
• Note the appearance of the "Main ends" string in the middle of the
output sequence
• > java MyThreadDemo
• 111111111122331122321122333331111Main ends111333222...
• This indicates that the main method has already finished
executing while thread 1, thread 2 and thread 3 are still running.
• Running a main method creates a thread.
• Normally, your program ends when the main thread ends.
• However, creating and then running a thread's start method
creates a whole new thread that executes its run() method
independent of the main method.
Pausing Thread
• Threads can be paused by the sleep() method.
• For example, to have MyThread pause for half a second
before it prints the next number, we add the following lines of
code to our for loop.
• Here, level specifies the new priority setting for the calling thread.
The value of level must be within the range MIN_PRIORITY and
MAX_PRIORITY.
Thread Priority
• Currently, these values are 1 and 10, respectively.
• i.e. final variable MIN_PRIORITY set as 1 and
• final variable MAX_PRIORITY set as 10
• To return a thread to default priority, specify NORM_PRIORITY,
which is currently 5.
• These priorities are defined as static final variables within Thread.
• Method setPriority to set priority of thread
RunableObj.ThreadObj.setPriority (NORM_PRIORITY + 2)
• Method getPriority to obtain current priority of thrread
RunableObj.ThreadObj.getPriority() returns integer between 1 to 10
class A extends Thread{
public void run(){
for(int i=1;i<=5;i++)
System.out.println("\t From Thread A: i="+i);
System.out.println("threadid of A"+currentThread().getId());
System.out.println("thread Priority of A"+currentThread().getPriority());
System.out.println("Exit A");
}
}
class MyPrinter {
public void print10(int value) {
for (int i = 0; i < 10; i++) {
System.out.print(value);
}
System.out.println(“ "); // newline after 10 numbers
}
}
MyPrinter
Instead of printing numbers directly, we use the print10() method in
MyThread, as shown by the following
class MyThread extends Thread {
int i;
MyPrinter p;
MyThread(int i) {
this.i = i;
p = new MyPrinter();
}
public void run() {
for (int ctr=0; ctr < 500; ctr++) {
p.print10(i);
}
}
}
• To achieve our goal there should not be any context switches
happening inside print10()
• Only a single thread should be allowed to execute inside print10()
• As can be seen, this is an example of the critical section
problem
• To solve this, we can use some of the techniques that
synchronize the code
Producer Consumer Problem
class Q{
int n;
boolean inStock=false;
synchronized void consumed(){
if (!inStock)
try{
wait();//tells the calling thread to give up the object q implicit moni and go to sleep until some other
thread that had object q's implicit moniter ,calls notify()
}
catch (InterruptedException e){ System.out.println("Caught ="+e);
}
System.out.println("Consumed="+n);
try{
Thread.sleep(1000);
}catch(InterruptedException e){
System.out.println("SleepExp="+ e);
}
inStock=false;
notify();
}
synchronized void produced(int nth){
if (inStock)
try{
wait();
}catch (InterruptedException e){
System.out.println("Caught ="+e);
}
System.out.println("Produced="+nth);
n=nth++;
inStock=true;
try{
Thread.sleep(1000);// 1000millisec
}catch(InterruptedException e){
System.out.println("SleepExp="+ e);
}
notify();
}
}
class Consumer implements Runnable{
class Producer implements Runnable{
Q qElement; Q qElement;
Producer(Q q){ Consumer(Q q){
Thread t = new Thread(this,"Producer"); Thread t = new Thread(this,"Consumer");
qElement=q; t.start(); qElement=q;
} t.start();
public void run(){ }
int element=1;
public void run(){
while(true)
while(true)
qElement.produced(element++);
qElement.consumed();
} }
} class ProdCon{ }
public static void main(String args[]){
Q q=new Q();
new Producer(q);
new Consumer(q);
System.out.println("Press Cntl-C to stop");
}
}
output
Press Cntl-C to
stop Produced=1
Consumed=1
Press Cntl-C to
stop Produced=2
Consumed=2
Press Cntl-C to
stop Produced=3
Consumed=3
Press Cntl-C to
stop Produced=4
Consumed=4
Press Cntl-C to
stop Produced=5
Consumed=5
Press Cntl-C to
stop