Multiprogramming
About 1 minNoteLanguageJava
- Multiprogramming
Running more than one programs on a single computer
Go read the Concurrency chapter of Thinking in Java
- By multiprogramming CPU's idle time is minimised
- A Thread of execution is the smallest sequence of programmed instructions that can be managed independently
- In many cases, a thread is a component of a process
- Useful for web server, GUI, animation, etc.
How to Implement Multithreading
extendsorimplementsor lambda expression- Depends on whether the subclass is inherited a superclass or not
ThreadclassRunnableinterface
Overriding the
run()methodrun()is the starting point of a thread
Start the thread
- If
implements Runnable,Thread t = new Thread(new Object()); t.start(); - If
extends Thread,o.start();
- If
Thread class
States of Thread

thread-states
Thread priority
- Scheduler in JVM maintains a thread ready queue
- The exact behaviour depends on the JVM
Constructors
Thread()Thread(Runnable r)Thread(Runnable r, String name)Thread(ThreadGroup g, String name)
Getter and setter
long getId()String getName()int getPriority()- Default priority of a thread (
NORM_PRIORITY) in Java is 5;MIN_PRIORITYis 1 andMAX_PRIORITYis 10
- Default priority of a thread (
ThreadState getState()ThreadGroup getThreadGroup()void setName(String name)void setPriority(int p)void setDaemon(boolean b)- A daemon thread is the background thread with least priority
- An example: garbage collector
Enquiry methods
boolean isAlive()boolean isDaemon()boolean isInterrupted()
Instance methods
void inerrupt()void join()- Wait for this thread to die
void join(long milli)void run()void start()
Static methods
int activeCount()- Returns an estimate of the number of active threads in the current thread's
ThreadGroupand its subgroups
- Returns an estimate of the number of active threads in the current thread's
Thread currentThread()- Returns a reference to the currently executing thread object.
void sleep(long milli)- Causes the currently executing thread to sleep
void yield()- A hint to the scheduler that the current thread is willing to yield its current use of a processor
void dumpStack()- Prints a stack trace of the current thread to the standard error stream
Synchronisation
- Shared resources
- Critical section
- Mutual exclusion
- Locking / mutex
- Semaphore
- Monitor
- Race condition
- Inter-thread communication
- How Java achieve synchronisation
- Object monitor
sychronized- Guard the critical section
- Synchronised method
- Synchronised block
- How Java achieve ITC
wait(),notify(),notifyAll()
