Pequeno resumo de sd
+-----------------+ +
| | |
| | |
| Main Thread | |
| | |
| | |
+----+---+---+----+ v
| | |
+---------------+ | +--------------+
| start start start |
| | |
| v |
+ +--+--------+ +-----+-------+ + +-----v-------+ +
| | | | | | | | |
| | Thread A +----> Thread B | | | Thread C | |
| | <----+ | | | | |
v +-----------+ +-------------+ v +-------------+ v
Threads may switch or exchange data/results
####Serving Multiple Clients Concurrently
+-------------------+
| |
+------+ Client 1 Process |
| | |
| +-------------------+
| +-------------------+
| | |
| | Client 2 Process +------+
| | | |
| +-------------------+ |
| |
| |
| |
| |
| |
| +-------------------+ |
| | | |
+------> Internet <------+
| |
+--^------------+---+
| |
| |
| |
| |
| |
+--+------------v---+
| |
| Server Process |
| |
| Server Threads |
| |
+-------------------+
+-----------------------------------+
| Process Parallelism |
+-----------------------------------+
+-----+ +-----+
| P1 | +---> +-----> +----> | CPU |
+-----+ +-----+
+-----+ +-----+
| P2 | +---> +-----> +----->+ CPU |
+-----+ +-----+
+-----+ +-----+
| P3 | +---> +-----> +----->+ CPU |
+-----+ +-----+
+ + + + + + + + +
+-----------------------------------+
+ + + + + + + + +
Time
- Concurrency vs Paralelism
+-----------------------------------+
| Process Parallelism |
+-----------------------------------+
+-----+
| P1 | +---> +-----> +---------+
+-----+ |
|
+-----+ +--v--+
| P2 | +---> +-----> +------> CPU |
+-----+ +--^--+
|
+-----+ |
| P3 | +---> +-----> +---------+
+-----+
+ + + + + + + + +
+-|---|---|---|---|---|---|---|---|-+
+ + + + + + + + +
Time
+-----------------------------------+
| Number of simultaneous execution |
| units ^ number of CPU's |
+-------+---------------------------+
- Java has built-in support for Multithreading
- Synxhronization
- Thread Scheduling
- Inter-Thread Communication:
- currentThread
- yield
- sleep
- start
- run
- stop
- setPriority
- getPriority
- suspend
- resume
- synchronized
- wait/notify/notifyAll
- Create a class that extends the Thread Class
- Create a class that implements the Runnable interface
+-----------+ +------------+
| Thread | | Runnable |
+----^------+ +-----^------+ +---------+
| | | Thread <--+
| | +----^----+ |
+----+------+ +-----+------+ | |
| My Thread | | MyClass +------------+ |
+-----------+ +-----+------+ |
| |
+---------------------------+
- Thread are object and must contains a method run()
class MyThread extends Thread
{
public void run()
{
// thread body of execution
}
}
- Create a thread:
MyThread thr1 = new MyThread();
- Start Execution of threads:
thr1.start();
- Create and Execute:
new MyThread().start();
class MyThread implements Runnable
{
public void run()
{
// thread body of execution
}
}
- Create a thread:
MyThread thr1 = new MyThread();
- Start Execution of threads:
thr1.start();
- Create and Execute:
new MyThread().start();
+---------+
| New |
+----+----+
| +-------------+
| | wait() |
+----v----+ | sleep() |
| start() | +------>+ suspend() +---+
+----+----- | | blocked | |
| | +-------------+ |
| | |
+----v----- | | +--------------+
| Runnable|<----> <---->| Non-runnable |
+----+----+ ^ | +--------------+
| | +-------------+ |
| | | notify() | |
+----v----+ | | slept | |
| stop() | +-------+ resume() <---+
+----+----+ | unblocked |
| +-------------+
|
+----v----+
| dead |
+---------+
class A extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("\t From ThreadA: i= "+i);
}
System.out.println("Exit from A");
}
}
class B extends Thread
{
public void run()
{
for(int j=1;j<=5;j++)
{
System.out.println("\t From ThreadB: j= "+j);
}
System.out.println("Exit from B");
}
}
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();
}
}
> java ThreadTest
From ThreadA: i= 1
From ThreadA: i= 2
From ThreadA: i= 3
From ThreadA: i= 4
From ThreadA: i= 5
Exit from A
From ThreadC: k= 1
From ThreadC: k= 2
From ThreadC: k= 3
From ThreadC: k= 4
From ThreadC: k= 5
Exit from C
From ThreadB: j= 1
From ThreadB: j= 2
From ThreadB: j= 3
From ThreadB: j= 4
From ThreadB: j= 5
Exit from B
> java ThreadTest
From ThreadA: i= 1
From ThreadA: i= 2
From ThreadA: i= 3
From ThreadA: i= 4
From ThreadA: i= 5
From ThreadC: k= 1
From ThreadC: k= 2
From ThreadC: k= 3
From ThreadC: k= 4
From ThreadC: k= 5
Exit from C
From ThreadB: j= 1
From ThreadB: j= 2
From ThreadB: j= 3
From ThreadB: j= 4
From ThreadB: j= 5
Exit from B
Exit from A
- The join() method used to wait until thread is done.
- The caller of join() blocks until thread finishes
- Why might this be bad ?
- Blocking the main thread will make UI freeze.
- Other versions of join take in a timeout value.
- if thread doesn't finish before timeout, join returns
- The sleep() method pauses execution of
the current thread.
- Implemented as a class method, so you don't actually need a Thread object
Thread.sleep(1000); //Pause here for 1 secound.
- Implemented as a class method, so you don't actually need a Thread object
- in Java, each thread is assigned priority, which affects the order in which is scheduled for running.
- The threads have a default priority (NORM_PRIORITY) and they are served using FCFS policy.
- Java allows users to change priority:
ThreadName.serPriority(int num);
MIN_PRIORITY = 1
NORM_PRIORITY = 5
MAX_PRIORITY = 10
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");
}
}
class C extends Thread{
public void run() {
System.out.println("Thread C started");
for(int k=1;k<=4;k++){ {
System.out.println("\t From ThreadC: k= "+k);
}
System.out.println("Exit from C");
}
}
class ThreadPriority{
public static void main(String args[]){
A threadA=new A();
B threadB=new B();
C threadC=new C();
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");
}
}
- On Solaris:
- A thread runs to complection or until a higher priority thread becames ready
- Preemption occurs (processor is given to the higher priority thread)
- On Win32:
- Threads are timesliced
- Thread given quantum of time to execute
- Processor then switches to any threads of equal priority
- Preemption occurs with higher and equal priority threads
- Threads are timesliced
To access to shared objects you need to use synchronized
keyword on the methods that are using a shared object
- 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()
{
...
}
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()
}
class MyThread implements Runnable {
Account account;
public MyThread (Account s) { account = s;}
public void run() { account.deposit(); }
} // end class MyThread
class YourThread implements Runnable {
Account account;
public YourThread (Account s) { account = s;}
public void run() { account.withdraw(); }
} // end class YourThread
class HerThread implements Runnable {
Account account;
public HerThread (Account s) { account = s; }
public void run() {account.enquire(); }
} // end class HerThread
- Every object has a lock associated with it.
- If you declare a method to be
syncronized
, the lock will be obtained before executing the method. - Use
syncronized
to make sure that only one thread at a time is accessing an object. - Example of syncronized method declaration:
syncronized int someMethot(int param)
class Account {
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.
}
}
- Methods associated with any object.
- wait(): a thread that is waiting at/on a particular object is suspended until some other thread wakes it.
- Every object maintains a list of "waiting" threads.
- notify() awakens a thread that is waiting.
synchronized (lock) {
while (!resourceAvailable()) {
lock.wait();
}
consumeResource();
}
produceResource();
synchronized (lock) {
lock.notifyAll();
}
produceResource();
synchronized (lock) {
lock.notify();
}
1. synchronized(lock){ +---------------+ 3. produceResource()
2. lock.wait(); +---> Lock Object <---+ 4. synchronized(lock) {
9. consumeResource(); | +---------------+ | 5. lock.notify();
10.} | | 6. }
| |
+------------------+ +---------------+
| |
+------+-------+ 7. Reacquire lock +--------+-------+
| Consumer | 8. Return from wait() | Producer |
| Thread | | Thread |
+--------------+ +----------------+