Java for C++ Programmers: Learning Multithreading in Java, Study notes of Operating Systems

A part of the 'java for c++ programmers' book by dr. Lixin tao. It covers the topic of multithreading in java, explaining its benefits, the thread class and interface runnable, thread methods and states, synchronization, and thread groups. It also includes code examples and explanations of thread-related methods and deprecated methods.

Typology: Study notes

Pre 2010

Uploaded on 08/09/2009

koofers-user-z1s
koofers-user-z1s 🇺🇸

10 documents

1 / 8

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
May 31, 2001
1© Dr. Lixin Tao, 2000
Java for C++ Programmers
Java for C++ Programmers © Dr. Lixin Tao, 2000 08-1
Multithread Computing
Java for C++ Programmers © Dr. Lixin Tao, 2000 08-2
About This Lecture
Purpose
To learn multithread programming in Java
What You Will Learn
¾
Benefits of multithreading
¾
Class Thread and interface Runnable
¾
Thread methods and thread state diagram
¾
Synchronization problem and its solution
¾
Thread groups
Java for C++ Programmers © Dr. Lixin Tao, 2000 08-3
Thread vs. Process
A thread is a function or method in
execution. It is represented by code,
program counter value, register values, and
its own method activation stack
A process is allocated system resources
like disk/memory space to perform a task. It
generates threads to execute code
Threads in a process can share data.
Synchronization and data protection are
programmers' responsibility. The benefit is
better performance due to finer user control.
Java for C++ Programmers © Dr. Lixin Tao, 2000 08-4
Benefits of Multithreading (1/2)
Multithreading on multiprocessor system leads to parallel
computing
Multithreading on a single processor may also benefit from
overlapping of running time on different function units
task 1
task 2
task 3
task 1
task 2
task 3
Java for C++ Programmers © Dr. Lixin Tao, 2000 08-5
Benefits of Multithreading (2/2)
On a single processor, multithreading
supports the illusion that several threads
are executing in parallel. The programmer
can thus focus on the subtask of each
thread, and let OS take care of detail how
the threads share the CPU
For interactive systems, multithreading is
almost the only way to make a system
remain responsive when heavy computing
is going on
Java for C++ Programmers © Dr. Lixin Tao, 2000 08-6
Threads are System-Dependent (1/2)
The scheduling of threads is system
dependent
On any system, a thread of higher priority
can preempt the CPU from a running thread
of lower priority
On Windows, round-robin time-sharing is
used. Each thread of the highest priority is
allocated a small time slice to run. When its
time slice is up, it gives up the CPU to
another thread of the same priority, and
waits for its next turn.
pf3
pf4
pf5
pf8

Partial preview of the text

Download Java for C++ Programmers: Learning Multithreading in Java and more Study notes Operating Systems in PDF only on Docsity!

Java for C++ Programmers (^) © Dr. Lixin Tao, 2000 08-

Multithread Computing

Java for C++ Programmers (^) © Dr. Lixin Tao, 2000 08-

About This Lecture

‹ Purpose

To learn multithread programming in Java

‹ What You Will Learn

¾ Benefits of multithreading

¾ Class Thread and interface Runnable

¾ Thread methods and thread state diagram

¾ Synchronization problem and its solution

¾ Thread groups

Java for C++ Programmers © Dr. Lixin Tao, 2000 08-

Thread vs. Process

‹ A thread is a function or method in

execution. It is represented by code,

program counter value, register values, and

its own method activation stack

‹ A process is allocated system resources

like disk/memory space to perform a task. It

generates threads to execute code

‹ Threads in a process can share data.

Synchronization and data protection are

programmers' responsibility. The benefit is

better performance due to finer user control.

Java for C++ Programmers © Dr. Lixin Tao, 2000 08-

Benefits of Multithreading (1/2)

‹ Multithreading on multiprocessor system leads to parallel

computing

‹ Multithreading on a single processor may also benefit from

overlapping of running time on different function units

task 1 task 2 task 3

task 1 task 2 task 3

Java for C++ Programmers © Dr. Lixin Tao, 2000 08-

Benefits of Multithreading (2/2)

‹ On a single processor, multithreading

supports the illusion that several threads

are executing in parallel. The programmer

can thus focus on the subtask of each

thread, and let OS take care of detail how

the threads share the CPU

‹ For interactive systems, multithreading is

almost the only way to make a system

remain responsive when heavy computing

is going on

Java for C++ Programmers © Dr. Lixin Tao, 2000 08-

Threads are System-Dependent (1/2)

‹ The scheduling of threads is system

dependent

‹ On any system, a thread of higher priority

can preempt the CPU from a running thread

of lower priority

‹ On Windows, round-robin time-sharing is

used. Each thread of the highest priority is

allocated a small time slice to run. When its

time slice is up, it gives up the CPU to

another thread of the same priority, and

waits for its next turn.

Java for C++ Programmers (^) © Dr. Lixin Tao, 2000 08-

Threads are System-Dependent (2/2)

‹ On Sun Solaris, the running thread will not give up CPU to threads of the same priority. As a result, programmers have to use yield() to let some thread voluntarily give up CPU from time to time to share CPU

‹ Java code should try to accommodate both thread models

‹ Our discussion will be based on round-robin time-sharing, which represents the future

Java for C++ Programmers (^) © Dr. Lixin Tao, 2000 08-

Class java.lang****. Thread

‹ For a simple thread that doesn't need to inherit from an

existing class, extend the thread class from

java.lang.Thread, and implement thread computation in

Thread method "void run()"

//User Defined Thread Class class UserThread extends Thread { …… public UserThread() { ……} public void run() { …… } }

//Client class public class Client { …… main() { UserThread ut = new UserThread(); ut.start(); …… } }

Java for C++ Programmers © Dr. Lixin Tao, 2000 08-

Interface java.lang.Runnable

‹ To make a derived class a thread, implement interface

Runnable

//User Defined Thread Class class UserThread extends X implements Runnable { …… public UserThread() { ……} public void run() { …… } }

//Client class public class Client { …… main() { Thread ut = new Thread(new UserThread()); ut.start(); …… } }

Java for C++ Programmers © Dr. Lixin Tao, 2000 08-

TestThreads.java (1/3)

public class TestThreads {

public static void main(String[] args) {

// Create threads

PrintChar printA = new PrintChar('a', 100);

PrintChar printB = new PrintChar('b', 100);

PrintNum print100 = new PrintNum(100);

// Start threads

print100.start();

printA.start();

printB.start();

Java for C++ Programmers © Dr. Lixin Tao, 2000 08-

TestThreads.java (2/3)

class PrintChar extends Thread { private char charToPrint; // The character to print private int times; // The times to repeat

public PrintChar(char c, int t) { charToPrint = c; times = t; }

public void run() { for (int i=0; i < times; i++) System.out.print(charToPrint); } } Java for C++ Programmers © Dr. Lixin Tao, 2000 08-

TestThreads.java (3/3)

class PrintNum extends Thread {

private int lastNum;

// Construct a thread for print 1, 2, ... i

public PrintNum(int n) {

lastNum = n;

public void run() {

for (int i=1; i <= lastNum; i++)

System.out.print(" " + i);

Java for C++ Programmers (^) © Dr. Lixin Tao, 2000 08-

Deprecated Thread Methods

‹ These methods can cause dead-locks, and therefore should be avoided (more later) ‹ Using these methods, or overriding them, will cause compilation warnings ‹ public void suspend()

¾ Suspends the thread, which will be awakened by

resume()

‹ public void resume()

¾ Awakens the suspended thread

‹ public void stop()

¾ Terminates the thread without reclaiming resources

Java for C++ Programmers (^) © Dr. Lixin Tao, 2000 08-

Thread State Diagram

Thread created

inactive

finished

running

ready

new

stop

run

yield, or time expired

stop, or complete stop

suspend, sleep, or wait

resume, notify, or notifyAll

start

Java for C++ Programmers © Dr. Lixin Tao, 2000 08-

Thread Group

‹ A thread group is a set of threads that can be manipulated together

¾ Create a new group

ThreadGroup g =

new ThreadGroup("UniqueGroupName);

¾ Add a thread to the group

Thread t = new Thread(g, new ThreadClass(),

"thread label");

¾ Find out number of active threads g.activeCount()

Java for C++ Programmers © Dr. Lixin Tao, 2000 08-

Thread Synchronization

‹ When multiple threads access a shared resource simultaneously, the shared resource may be corrupted. Keyword synchronized may help ‹ If a method is qualified by "synchronized" but not by "static", any time only one of such methods can be invoked on a particular object of the class type; but two invocations of such synchronized methods can happen at the same time if they are on different objects ‹ If a method is qualified by "static synchronized", any time only one of such methods can be invoked on any object of this class type

Java for C++ Programmers © Dr. Lixin Tao, 2000 08-

Example for Resource Conflict

‹ PiggyBankWithoutSync.java contains an instance of PiggyBank, and 100 threads of AddAPennyThread

‹ Due to shared data access, different run has different final balance

Java for C++ Programmers © Dr. Lixin Tao, 2000 08-

PiggyBankWithoutSync.java (1/3)

public class PiggyBankWithoutSync { private PiggyBank bank = new PiggyBank(); private Thread[] thread = new Thread[100];

public static void main(String[] args) { PiggyBankWithoutSync test = new PiggyBankWithoutSync(); System.out.println("Final balance is " + test.bank.getBalance()); }

public PiggyBankWithoutSync() { ThreadGroup g = new ThreadGroup("group"); boolean done = false;

for (int i = 0; i < 100; i++) { thread[i] = new Thread(g, new AddAPennyThread(), "t"); thread[i].start(); }

Java for C++ Programmers (^) © Dr. Lixin Tao, 2000 08-

PiggyBankWithoutSync.java (2/3)

while (!done) if (g.activeCount() == 0) done = true; } class AddAPennyThread extends Thread { public void run() { int newBalance = bank.getBalance() + 1; try { Thread.sleep(5); } catch (InterruptedException e) { System.out.println(e); } bank.setbalance(newBalance); } } } Java for C++ Programmers (^) © Dr. Lixin Tao, 2000 08-

PiggyBankWithoutSync.java (3/3)

class PiggyBank { private int balance = 0;

public int getBalance() { return balance; }

public void setbalance(int balance) { this.balance = balance; } }

Java for C++ Programmers © Dr. Lixin Tao, 2000 08-

PiggyBankWithSync.java (modified part)

public class PiggyBankWithSync { …… // next line "static" can be dropped private static synchronized void addAPenny(PiggyBank bank) { int newBalance = bank.getBalance() + 1; try { Thread.sleep(5); } catch (InterruptedException e) { System.out.println(e); } bank.setbalance(newBalance); } class AddAPennyThread extends Thread { public void run() { addAPenny(bank); } } } Java for C++ Programmers © Dr. Lixin Tao, 2000 08-

Monitor (1/4)

‹ To ensure object data integrity, some methods cannot be executed by more than one thread at a time ‹ Java uses monitor to support data protection. Each class has one class monitor for the class, and one object monitor for each object of the class ‹ The class monitor controls the access of threads to the static synchronized methods of the class ‹ An object monitor controls the access of threads to the non-static synchronized methods of an object of the class

Java for C++ Programmers © Dr. Lixin Tao, 2000 08-

Monitor (2/4)

‹ Each monitor has one lock and one key to control access to its synchronized methods. Only a thread holding the key can access these methods ‹ When no thread is executing in a monitor, the key is available. A thread grabs the key to execute in the monitor, holding the key. Upon exiting from the monitor, the thread returns the key ‹ Each monitor has two queues: the entry queue for threads waiting for the key to access the monitor, and the wait queue for threads that are blocked by invoking wait() when they were executing in a synchronized method Java for C++ Programmers © Dr. Lixin Tao, 2000 08-

Monitor (3/4)

‹ (^) When a thread invokes a synchronized method of a class, it first waits in the entry queue of the corresponding monitor ‹ If the key is available, the thread takes it and starts executing in the monitor. Otherwise it waits ‹ If the running thread exits the method, it returns the key, and the thread with the highest priority in the entry queue will take the key and start its execution in the monitor ‹ If the running thread calls wait(), it suspends itself on the wait queue, and releases the key for other threads in the entry queue to execute in the monitor

Java for C++ Programmers (^) © Dr. Lixin Tao, 2000 08-

Rewrite Deprecated Methods (3/4)

‹ Assume a boolean variable dedicated to this thread boolean suspended = false;

public synchronized void myResume() { if (suspended) { suspended = false; notifyAll(); } } Java for C++ Programmers (^) © Dr. Lixin Tao, 2000 08-

Rewrite Deprecated Methods (4/4)

public synchronized void myStop() thread = null; notifyAll(); } void run() { …… if (thread == null) termination Processing ; }

Java for C++ Programmers © Dr. Lixin Tao, 2000 08-

ThreadSynch.java (1/7)

// ThreadSynch.java demonstrates how to simulate the deprecated methods // suspend(), resume(), and stop(). It creates 3 threads, each prints random // letters. User can suspend or resume each thread with mouse. import java.awt.; import java.awt.event.; import javax.swing.*;

public class ThreadSynch extends JApplet implements Runnable, ActionListener { private String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; private JLabel outputs[]; private JCheckBox checkboxes[]; private final static int SIZE = 3; private Thread threads[]; private boolean suspended[]; Java for C++ Programmers © Dr. Lixin Tao, 2000 08-

ThreadSynch.java (2/7)

public void init() { outputs = new JLabel[SIZE]; checkboxes = new JCheckBox[SIZE]; threads = new Thread[SIZE]; suspended = new boolean[SIZE]; Container c = getContentPane(); c.setLayout(new GridLayout(SIZE, 2, 5, 5)); for (int i = 0; i < SIZE; i++) { outputs[i] = new JLabel(); outputs[i].setBackground(Color.green); outputs[i].setOpaque(true); c.add(outputs[i]); checkboxes[i] = new JCheckBox("Suspended"); checkboxes[i].addActionListener(this); c.add(checkboxes[i]); } }

Java for C++ Programmers © Dr. Lixin Tao, 2000 08-

ThreadSynch.java (3/7)

public void start() { // create threads and start every time start is called for (int i = 0; i < threads.length; i++) { threads[ i ] = new Thread( this, "Thread " + (i + 1) ); threads[ i ].start(); } }

public void run() { Thread currentThread = Thread.currentThread(); int index = getIndex(currentThread); char displayChar;

Java for C++ Programmers © Dr. Lixin Tao, 2000 08-

ThreadSynch.java (4/7)

while (threads[index] == currentThread) { // check for stopping the thread // sleep from 0 to 1 second try { Thread.sleep((int)(Math.random()*1000));

synchronized(this) { while (suspended[index] && threads[index] == currentThread) wait(); } } catch (InterruptedException e) { System.err.println("sleep interrupted"); }

Java for C++ Programmers (^) © Dr. Lixin Tao, 2000 08-

ThreadSynch.java (5/7)

displayChar = alphabet.charAt((int)(Math.random()*26 )); outputs[index].setText(currentThread.getName() + ": " + displayChar ); } System.err.println( currentThread.getName() + " terminating"); }

private int getIndex(Thread current) { for (int i = 0; i < threads.length; i++) if (current == threads[i]) return i;

return -1; } Java for C++ Programmers (^) © Dr. Lixin Tao, 2000 08-

ThreadSynch.java (6/7)

public synchronized void stop() { // stop threads every time stop is called // as the user browses another Web page for (int i = 0; i < threads.length; i++) threads[ i ] = null;

notifyAll(); }

Java for C++ Programmers © Dr. Lixin Tao, 2000 08-

ThreadSynch.java (7/7)

public synchronized void actionPerformed( ActionEvent e ) { for ( int i = 0; i < checkboxes.length; i++ ) { if (e.getSource() == checkboxes[i]) { suspended[i] = !suspended[i]; outputs[i].setBackground( !suspended[i]? Color.green : Color.red); if (!suspended[i]) notifyAll(); return; } } } }

Java for C++ Programmers © Dr. Lixin Tao, 2000 08-

ThreadSynch.html