Athipathy Threads in Java

You might also like

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 25

04/16/09 Vimal 1

Threads
Why use threads??
It is a powerful programming tool
 Computer users take it for granted that their
systems can do more than one thing at a time.
 They assume that they can continue to work in a
word processor, while other applications download
files, manage the print queue, and stream audio.
 Even a single application is often expected to do
more than one thing at a time.
 Example of a web server: Many clients
accessing….impossible to handle without threads!
04/16/09 Vimal 2
Use of threads cont..

 In Internet: 100 simultaneous connections means


100 processes to handle. Just imagine 100 million
internet users!!
 Similarly with web servers..performance crawls
with more simultaneous connections

04/16/09 Vimal 3
Another example
 Streaming audio application must simultaneously
read the digital audio off the network, decompress
it, manage playback, and update its display.
 Even the word processor should always be ready to
respond to keyboard and mouse events, no matter
how busy it is reformatting text or updating the
display.
 Software that can do such things is known as
concurrent software.

04/16/09 Vimal 4
Concurrent programming
 The Java platform is designed from the ground up
to support concurrent programming, with basic
concurrency support in the Java programming
language and the Java class libraries.

 Since version 5.0, the Java platform has also


included high-level concurrency APIs in the
java.util.concurrent packages.

04/16/09 Vimal 5
Concurrency vs. Parallelism
CPU
CPU1 CPU2

main RAM
main
run

main

run this.count run

main
run
main
main

04/16/09 Vimal 6
Process & threads
 In concurrent programming, there are two basic
units of execution: processes and threads.
 In the Java programming language, concurrent
programming is mostly concerned with threads.
However, processes are also important. Threads are
light weight processes!
 A computer system normally has many active
processes and threads. This is true even in systems
that only have a single execution core, and thus only
have one thread actually executing at any given
moment.
 Processing time for a single core is shared among
processes and threads through an OS feature called
time slicing.
04/16/09 Vimal 7
What is a thread?
 A thread is like a sequential
program.
 A single thread has a
beginning, a sequence, and an
end and at any given time
during the runtime of the
thread, there is a single point
of execution.
 However, a thread itself is not
a program; it cannot run on its
own. Rather, it runs within a
program.

04/16/09 Vimal 8
Multiple threads

04/16/09 Vimal 9
Creating Threads
Two ways of creating threads:
 Extending a class.
 Implementing an interface
 Extending a class is the way Java inherits
methods and variables from a parent class.
In this case, one can only extend or inherit
from a single parent class.
 This limitation within Java can be
overcome by implementing interfaces, which
is the most common way to create threads.
04/16/09 Vimal 10
Implementing thread

 start()
 run()
 To get information from a finished thread is a
challenge especially in a multi-threaded system
 return - is used

04/16/09 Vimal 11
Extending a class

1. import java.util.*;
2. class TimePrinter extends Thread {
3. int pauseTime;
4. String name;
5. public TimePrinter(int x, String n)
6. { pauseTime = x; name = n; }
7. public void run()
8. {
9. while(true) {
10. try {
11. System.out.println(name + ":" + new
Date(System.currentTimeMillis()));
12. Thread.sleep(pauseTime); } catch(Exception e) { }
13. } }
04/16/09 Vimal 12
 public static void main(String args[]) {
 TimePrinter tp1 = new TimePrinter(1000,
"Fast Guy");
 tp1.start();
 TimePrinter tp2 = new TimePrinter(3000,
"Slow Guy");
 tp2.start();
 }}

04/16/09 Vimal 13
Implementing Runnable interface
 import java.util.*;
 class TimePrinter implements Runnable {
 int pauseTime;
 String name;
 public TimePrinter (int x, String n)
 { pauseTime = x; name = n; }
 public void run() { while(true) {
 try {
 System.out.println(name + ":" + new
Date(System.currentTimeMillis()));
Thread.sleep(pauseTime);
 } catch(Exception e) { }

04/16/09 } } Vimal 14
cont

1. public static void main(String


args[]) {
2. Thread t1 = new Thread(new
TimePrinter(1000, "Fast Guy"));
t1.start();
3. Thread t2 = new Thread(new
TimePrinter(3000, "Slow Guy"));
t2.start();
4. } }
04/16/09 Vimal 15
04/16/09 Vimal 16
Creating Multiple threads
Class newThread implements Runnable
{ String name;Thread t;
NewThread(String threadname)
{ name=threadname;
t=newThread(this,name);
System.out.println(“New Thread:”+t);
t.start();
}
public void run()
{

04/16/09 Vimal 17
Cont..

try{
For(int i=00;i>0;i--)
{ System.out.println(name +”:”+i);
Thread.sleep(1000);
}catch(IntrrruptedException e){}
System.out.println(name +’exiting);
}
}

04/16/09 Vimal 18
Cont..
Class MultiThreadDemo
{
public static void main(String args[])
{
new NewThread(“one”);
new NewThread(“two”);
new NewThread(“three”);
try{
Thread.sleep(10000);
}catch(InterruptedException e){}
}}

04/16/09 Vimal 19
Synchronization

 Two or more threads accessing the same data


simultaneously may lead to loss of data integrity.
 Java uses the concept of semaphore or monitor to
enable this.
 Monitor is an object used as a mutually exclusive
lock.
 Synchronized

04/16/09 Vimal 20
 Class Consumer implements Runnable {
 Stock c; C
 Thread t;
o
 Consumer (Stock c)
n
 { this.c=c;
 t=new Thread(this,”consumer thread”);
s
 t.start(); } u
 public void run(){ m
 while(true){ e
 try{ r.
 t.sleep(750); j
 }catch(InterruptedEcception e){} a
 c.getStock((int)(Math.random()*100));
v
 } }
a21
void stop(){ t.stop() } } Vimal
04/16/09
 Class Producer implements Runnable {
 Stock c; P
 Thread t;
r
 Producer (Stock c)
o
 { this.c=c;
 t=new Thread(this,”producer thread”);
d
 t.start(); } u
 public void run() { c
 while(true) { e
 try{ r.
 t.sleep(750); j
 }catch(InterruptedExcception e){} a
 c.getStock((int)(Math.random()*100)); v
 } }
a
 void stop(){ t.stop() } } Vimal
04/16/09 22
Stock.java
1. Class Stock {
2. int goods=0;
3. Public synchronized void addStock(int i)
4. { goods=goods+i;
5. System.out.println(“Stock added:”+i);
6. System.out.println(“Present Stock:”+goods);
7. notify();
8. }
9. public synchronised int getStock(int j)
10. { while(true)
11. {
04/16/09 Vimal 23
• if(goods >=j)
• { goods=goods=goods-j;
• System.out.println(“Stock taken away:”+i);
• System.out.println(“Present Stock:”+goods);
• break;
• }else {
• System.out.println(“Stock not enough:”+i);
• System.out.println(“Waiting for stocks to
come:”+goods);
• try {
• wait();
• }catch(InterruptedException e){}
• }}
• return goods; }

04/16/09 Vimal 24
• public static void main(String args[])
• { Stock= new Stock();
• Producer p= new Producer(j);
• Consumer c=new Consumer(j);
• try{
• Thread.sleep(10000);
• p.stop();
• c.stop();
• }catch(InterrruptedException e){}
• }
• }
04/16/09 Vimal 25

You might also like