Skip to content

Instantly share code, notes, and snippets.

@danielgek
Created January 18, 2016 02:34
Show Gist options
  • Save danielgek/32e58b1c0c4c999cc342 to your computer and use it in GitHub Desktop.
Save danielgek/32e58b1c0c4c999cc342 to your computer and use it in GitHub Desktop.

SD

Pequeno resumo de sd

Java Threads

Multithreaded Program

                 +-----------------+   +
                 |                 |   |
                 |                 |   |
                 |   Main Thread   |   |
                 |                 |   |
                 |                 |   |
                 +----+---+---+----+   v
                      |   |   |
      +---------------+   |   +--------------+
      |  start         start           start |
      |                   |                  |
      |                   v                  |
+  +--+--------+    +-----+-------+ +  +-----v-------+  +
|  |           |    |             | |  |             |  |
|  |  Thread A +---->  Thread B   | |  |  Thread C   |  |
|  |           <----+             | |  |             |  |
v  +-----------+    +-------------+ v  +-------------+  v
     Threads may switch or exchange data/results

Multithreaded Server:

####Serving Multiple Clients Concurrently

       +-------------------+
       |                   |
+------+ Client 1 Process  |
|      |                   |
|      +-------------------+
|      +-------------------+
|      |                   |
|      | Client 2 Process  +------+
|      |                   |      |
|      +-------------------+      |
|                                 |
|                                 |
|                                 |
|                                 |
|                                 |
|      +-------------------+      |
|      |                   |      |
+------> Internet          <------+
       |                   |
       +--^------------+---+
          |            |
          |            |
          |            |
          |            |
          |            |
       +--+------------v---+
       |                   |
       | Server Process    |
       |                   |
       | Server Threads    |
       |                   |
       +-------------------+


Multithreading - Multiprocessors

+-----------------------------------+
|  Process Parallelism              |
+-----------------------------------+
+-----+                       +-----+
| P1  | +--->  +-----> +----> | CPU |
+-----+                       +-----+

+-----+                       +-----+
| P2  | +--->  +-----> +----->+ CPU |
+-----+                       +-----+

+-----+                       +-----+
| P3  | +--->  +-----> +----->+ CPU |
+-----+                       +-----+

  +   +   +   +   +   +   +   +   +
+-----------------------------------+
  +   +   +   +   +   +   +   +   +
                Time

Multithreading: Single processor

  • Concurrency vs Paralelism
+-----------------------------------+
|  Process Parallelism              |
+-----------------------------------+
+-----+
| P1  | +--->  +-----> +---------+
+-----+                          |
                                 |
+-----+                       +--v--+
| P2  | +--->  +-----> +------> CPU |
+-----+                       +--^--+
                                 |
+-----+                          |
| P3  | +--->  +-----> +---------+
+-----+

  +   +   +   +   +   +   +   +   +
+-|---|---|---|---|---|---|---|---|-+
  +   +   +   +   +   +   +   +   +
                Time

+-----------------------------------+
| Number of simultaneous execution  |
| units ^ number of CPU's           |
+-------+---------------------------+


Java Threads

  • 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

Creating Threads

  • Create a class that extends the Thread Class
  • Create a class that implements the Runnable interface
+-----------+    +------------+
| Thread    |    | Runnable   |
+----^------+    +-----^------+       +---------+
     |                 |              | Thread  <--+
     |                 |              +----^----+  |
+----+------+    +-----+------+            |       |
| My Thread |    | MyClass    +------------+       |
+-----------+    +-----+------+                    |
                       |                           |
                       +---------------------------+

Option A: Extend Thread Class
  • 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();
Option B Implements Runnable:
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();

Life cycle of a Thread

+---------+
|  New    |
+----+----+
     |                  +-------------+
     |                  | wait()      |
+----v----+             | sleep()     |
| start() |     +------>+ suspend()   +---+
+----+-----     |       | blocked     |   |
     |          |       +-------------+   |
     |          |                         |
+----v-----     |                         |     +--------------+
| Runnable|<---->                         <---->| Non-runnable |
+----+----+     ^                         |     +--------------+
     |          |       +-------------+   |
     |          |       | notify()    |   |
+----v----+     |       | slept       |   |
| stop()  |     +-------+ resume()    <---+
+----+----+             | unblocked   |
     |                  +-------------+
     |
+----v----+
| dead    |
+---------+

Code example with 3 threads

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();
	}
}

Executions:

Execution 1:

> 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

Execution 1:

> 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

join() Method:

  • 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

sleep() Method:

  • 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.

Thread Priority

  • 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
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");
	}
}

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");
	}
}
Thread priorities
  • 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

Access to shared objects:

To access to shared objects you need to use synchronized keyword on the methods that are using a shared object

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()
{
	...
}
3 Thread sharing the same object example:
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

Access syncronization
  • 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)
Syncronized access to shared object
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.
	}
}

wait() and notify() methods:

  • 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.
Consumer:
synchronized (lock) {
	while (!resourceAvailable()) {
		lock.wait();
	}
	consumeResource();
}
Producer:
produceResource();
synchronized (lock) {
	lock.notifyAll();
}


produceResource();
synchronized (lock) {
	lock.notify();
}
wait/notify sequence
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     |
+--------------+                                         +----------------+

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment