Object-oriented
programming (Threads)
By: Michael SB
Outline
• Concurrency
• Processes
• Threads
Concurrency
• Two or more tasks are said to be concurrently executing, when all tasks are
progressing at the same time.
• Parallelism:
• Is subset of concurrency.
• Occurs when two or more tasks are executing simultaneously.
Processes
• Processes are programs in execution.
• Processes have their own:
• State: New, Ready, Running, Waiting, and Terminated
• Memory
• Will be allocated time on CPU when they become active
Threads
• Threads are segments in processes.
• They are a single sequential flow of execution within a single process.
• Threads have their own:
• Stack
• Program counter
Threads Vs Process
• Threads:
• Can share memory with each other.
• Can share resources allocated to the process: memory
• Less time to communicate with other threads
• Less time to create, switch context, and terminate threads
Threads
• Thread states:
• Created State
• Running State
• Waiting State
• Timed-waiting
• Blocked state
• Terminated state
Threads in Java
• We use a thread object which is an instance of the thread class to create a new thread
in Java.
• The constructor of a thread object accepts a class implementing the runnable
interface.
• The alternative way is, extending the thread class and overriding the methods.
Creating Threads
Output
Controlling Threads
Sleep: causes the current thread to wait for a designated period of time. Throws
interrupted exception.
Interrupt
• Interrupt: wakes up a thread in sleep() or wait() or blocked by an IO operation.
Problem
Problem
Problem
Output
Synchronization
• Thread synchronization: coordinates access to shared data by multiple concurrent
threads.
• By synchronizing threads, you can ensure that each thread accessing a shared object
excludes all other threads from doing so simultaneously—this is called mutual
exclusion.
• A common way to perform synchronization is to use Java’s built-in monitors. The
monitor ensures that its object’s monitor lock is held by a maximum of only one
thread at any time.
Synchronization
Output
Reading Assignment
• File i/o: will be included in the final exam.
• Practice threads with example, and look into inter-thread communication with wait(),
notify(), and notifyAll(): This will not be included in the final exam.
Final exam
• Maximum point: 30%
• Question type: similar to mid-exam
• Topics (includes: File I/O and all the topics discussed in lectures and labs except
lecture 0. )
• Lecture 1 to Lecture 3
• SOLID, Threads, and File I/O