




Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
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
1 / 8
This page cannot be seen from the preview
Don't miss anything!





Java for C++ Programmers (^) © Dr. Lixin Tao, 2000 08-
Java for C++ Programmers (^) © Dr. Lixin Tao, 2000 08-
Java for C++ Programmers © Dr. Lixin Tao, 2000 08-
Java for C++ Programmers © Dr. Lixin Tao, 2000 08-
task 1 task 2 task 3
task 1 task 2 task 3
Java for C++ Programmers © Dr. Lixin Tao, 2000 08-
Java for C++ Programmers © Dr. Lixin Tao, 2000 08-
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
//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
//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)
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)
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()
public void resume()
public void stop()
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
¾ 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