+ All Categories
Home > Education > java threads

java threads

Date post: 16-Apr-2017
Category:
Upload: waheed-warraich
View: 163 times
Download: 0 times
Share this document with a friend
79
Topic 12: Multithreading Volume II,Chapter 1 Advanced Programming Techniques
Transcript
Page 1: java threads

Topic 12: Multithreading Volume II,Chapter 1

Advanced Programming Techniques

Page 2: java threads

Outline• Introduction: Why and what• Basics: creating and running threads

• Issues– Thread states– Thread scheduling– Synchronization– Suspending and stopping threads

• Uses– Animation– Threads and Swing

Page 3: java threads

Introduction

• Consider the program Bounce.java– Desired effects

• If the Start button is clicked, a ball starts to bounce.

• If the button is clicked again, a second ball starts to bounce and so on.

• If the Close button is clicked, the windows closes and the program terminates

– Classes• Ball• BallCanvas extends JPanel• BounceFrame• Bounce

Page 4: java threads

Introduction– Classes

• Ball– public void draw(Graphics2D g2)

» Draws the ball at its current position– public void move()

» Moves the ball to the next position, reversing direction if it hits one of the edges

» Request paint afterwards to update UI

• class BallCanvas extends JPanel– Keeps a list of balls– public void add(Ball b)

» Add a ball to the canvas.– public void paintComponent(Graphics g)

» Draw all balls at their current positions

Page 5: java threads

Introduction– Classes

• class BounceFrame extends JFrame– Set up GUI and listeners– When the Close button is clicked this method is called, public void actionPerformed(ActionEvent evt) { System.exit(0); }

– When the Start Button is clicked, this method is called public void actionPerformed(ActionEvent evt) { addBall(); // Creates and adds a bouncing ball to the canvas

// and make it bounce 1,000 times. }

Page 6: java threads

Introduction public void addBall() { try {

Ball b = new Ball(canvas); // create a ball canvas.add(b); // add it to the canvas

// bounce it 1,000 times for (int i = 1; i <= 1000; i++) { b.move(); Thread.sleep(5); // sleep for 5 milliseconds }}

catch (InterruptedException exception){} }

Note: sleep is a static method that puts the currently running thread to sleep. It throws InterruptedException when interrupted.

Page 7: java threads

Introduction• However

– Cannot start a second ball before the current ball finishes bouncing

– Cannot terminate program before the current ball finishes bouncing

– Actually, won’t even work if repaint is used (as it should be) instead of paint (see end of Bounce.java)!!!!!

Page 8: java threads

Introduction Why?

There is a single thread of control.

Actions are executed one by one.

Cannot execute next action before current action finishes

Implications in general: Cannot do anything else while waiting data from the net. Cannot stop downloading even though you know, after seeing

part of the download, that you don’t want the download any more

Solution: Multithreading

Page 9: java threads

Introduction

• A multithreaded program has multiple threads of control– OS runs one thread a short period of time, then switches to another, and so on– To user, threads appear to run simultaneously. An illusion.– Nonetheless, makes it easier for user to interact with program

Page 10: java threads

Introduction In our example, we need more than one thread:

One thread to listen for button clicks

One thread to bounce each ball

//BounceThread.java

Page 11: java threads

Outline• Introduction: Why and what• Basics: creating and running threads

• Issues– Thread states– Thread scheduling– Synchronization– Suspending and stopping threads

• Uses– Animation– Threads and Swing

Page 12: java threads

Creating and Running Threads• How to create and run new threads (from the current thread)?

– Write a class for thread• Either a class that extends the class java.lang.Thread class MyThreadClass extends Thread {…} • Or a class that implements the interface java.lang.Runnableclass MyRunnableClass implements Runnable { ….}

• Specify what the new thread should do in the method void run()class MyThreadClass extends Thread { public void run() {// codes for new thread to run }…}

Page 13: java threads

Creating and Running Threads• How to create and run new threads?

– Create an object of the thread classMyThreadClass t = new MyThreadClass();Thread t = new Thread( new MyRunnableClass() );

– Start a new thread by calling the start methodt.start()

– Notes:• Don’t call run directly. “run” does not create

new thread• “start” does thread setup and calls “run”

Page 14: java threads

Creating and Running Threads• In our example, we want a separate thread to bounce each ball. So we first define this

thread class

class BallThread extends Thread{ public BallThread(Ball aBall) { b = aBall; }

public void run() // codes for new thread { try { for (int i = 1; i <= 1000; i++) { b.move(); sleep(5); }} catch (InterruptedException exception { } } private Ball b;}

Page 15: java threads

Creating and Running Threads• Next, we modify the addBall method of BounceFrame to

– add a bouncing ball to the canvas and – start a thread to make it bounce

public void addBall() { Ball b = new Ball(canvas); canvas.add(b);

BallThread thread = new BallThread(b); thread.start(); }

// BounceThread.java// try to replace start with run and see what happens

Page 16: java threads

Creating and Running Threads

• Event dispatch thread– Why?

• In BounceThread.java, the move method calls repaint()• In Bounce.java, the move method calls paint(canvas.getGraphics());

– Any program starts in the main thread, when the main method is called– In a GUI program, the main thread creates a window and a event dispatch thread

to handle events. It usually dies thereafter.– repaint() generates an PaintEvent, which is handled by the event dispatch thread.

• In Bounce.java, the event dispatch thread is consumed by the addBall operation for 5 seconds

• During that time, it cannot handle any events. It does not handle paint event.

• So, the ball would not be painted if repaint() was used instead of paint.

Page 17: java threads

Creating and Running Threads RunnableTest.java

class RadioButtonDemo extends JPanel implements Runnable { … public void run () { // display images one by one }

public void showPicture(){ if (runner == null) { runner = new Thread(this); // create thread runner.start(); // run thread }}private Thread runner;

…}

Page 18: java threads

Invoke the showPicture method

showButton.addActionListener(new ActionListener(){

public void actionPerformed( ActionEvent e) {

showNow = true;showPicture();

}}

);

Creating and Running Threads

Page 19: java threads

Outline• Introduction: Why and what• Basics: creating and running threads

• Issues– Thread states– Thread scheduling– Synchronization– Suspending and stopping threads

• Uses– Animation– Threads and Swing

Page 20: java threads

Thread States Four states for threads: new, runnable, blocked, dead

newstart

dead

Note: suspend, resume,stop deprecated.

runnable

run exitsstop

blocked

sleep

done sleepingsuspend

resumewait notify

block on I/O

I/O complete

Wait for lockLock available

Page 21: java threads

Thread States When a thread has just been created using the new operator, it is in

the new state.

Once start method is invoked (which calls the run method), the thread becomes runnable. A runnable thread might not be running. There can be many runnable threads. But only one of them can be

running at any time point. OS decides which thread to run. More on this later.

new

runnable

start

Page 22: java threads

Thread States A runnable thread enters the blocked state when

1. The thread is currently running and method Thread.sleep is called 2. suspend method of the thread is called. (deprecated)3. The thread calls the wait method.4. The thread tries to lock an object locked by another thread.5. The thread calls an operation that is blocked on i/o.

runnable

blocked

sleep

suspend

wait

block on I/O

Wait for lockA blocked thread cannot be running

Page 23: java threads

Thread States A blocked reenters runnable state when

1. It has slept the specified amount of time.2. resume method of the thread is called. (deprecated)3. Another method calls notify or notifyAll 4. Object lock released by other thread5. I/O completed.

runnable

blockeddone sleeping

resume

notify

I/O completeLock available

Page 24: java threads

Thread States A runnable thread enters the dead state when

Its run method exits. Natural death. stop method of the thread is called. (deprecated) An exception is thrown but not caught.

dead

runnable

run exitsstop

Page 25: java threads

Thread States

• Finding out states of threads

– Method isAlive allows you to find out whether a thread is alive of dead.

• This method returns true if the thread is runnable or blocked,

• false if the thread is still new and not yet runnable or if the thread is dead

– No way to find out whether an alive thread is running, runnable, or blocked.

Page 26: java threads

Outline• Introduction: Why and what• Basics: creating and running threads

• Issues– Thread states– Thread scheduling– Synchronization– Suspending and stopping threads

• Uses– Animation– Threads and Swing

Page 27: java threads

Thread Scheduling• At any time, there might be many runnable threads. But only one of them is actually

running.• The thread scheduler decides which runnable thread to run.

• Questions:– When does the thread scheduler kick in and pick a thread to run?– How does the thread scheduler select among the runnable threads?

• A not-so-precise answer:– A running Java thread will continue to run until

• It calls yield method, or• It ceases to be runnable (dead or blocked), or • Another thread with higher priority moves out of blocked state

– Then the thread scheduler kicks in and picks another thread with the highest priority to run

Page 28: java threads

Thread Scheduling Two different thread implementations

“Native thread” implementation (e.g. Windows): Performs time-slicing. Interrupts the running thread periodically to

give other threads a chance to run.

“Green thread” implementation (e.g. Solaris) Does not perform time-slicing. It keeps a running thread active until

a higher-priority thread awakes and takes control.

Page 29: java threads

Thread Scheduling The answer on slide 17 is precise for the green thread

implementation.

For the native thread implementation, the precise answer is A running Java thread will continue to run until

– It calls yield method, or– It ceases to be runnable (dead or blocked), or– Another thread with higher priority moves out of blocked state,

or– It is pre-emptied by OS (time-slicing).

Then the thread scheduler kicks in and picks another thread with the highest priority to run

Page 30: java threads

Thread Scheduling

• Priority of individual threads– Can be increased or decreased using setPriority

• Java have 10 priority levels (constants of Thread class)MIN_PRIORITY = 1; NORMAL_PRIORITY = 5;MAX_PRIORITY = 10

– A thread inherits priority from its parent thread, the one the creates it.

– Note• Some OS has fewer. E.g. Windows NT has 7.• JVM maps Java priority levels to priority level of the underlying OS.

Page 31: java threads

Example: BounceExpress.java Two kinds of balls: black and red. Red ball threads have higher priority and hence get more

chance to run. The effect is that red balls appear to be faster.

Thread Scheduling

Page 32: java threads

Thread Scheduling

• The addBall method public void addBall(int priority, Color color)

{ Ball b = new Ball(canvas, color); canvas.add(b);

BallThread thread = new BallThread(b);

thread.setPriority(priority); thread.start(); }

Page 33: java threads

Thread Scheduling• Buttons and listeners

addButton(buttonPanel, "Start", new ActionListener() { public void actionPerformed(ActionEvent evt) { addBall(Thread.NORM_PRIORITY, Color.black); }});

addButton(buttonPanel, "Express", new ActionListener() { public void actionPerformed(ActionEvent evt) { addBall(Thread.NORM_PRIORITY + 2, Color.red); } });

Page 34: java threads

Thread Scheduling• Question 1:

– Consider the case when there are 1 black ball and 1 red ball.– When the red-ball thread goes to sleep, there is only one other thread, the

black-ball thread. – Hence the black-ball thread must be chosen.– Implication:

• black ball takes one move, red ball takes one move, black ball takes one move, and so on.

• The two balls should be of the same speed.– Well, this is not the case. Why?

– There is another thread! What is it? What role does it play?– When event dispatch thread pauses, the red-ball thread already wake up from

sleep and hence picked by scheduler over back-ball thread.

– (Is pre-emption a reason?)

Page 35: java threads

Thread Scheduling

• Question 2:– If we change sleeping to 50, red balls are not

faster any more.– Why?– In order for the red-ball thread to be picked more

often than the black-ball thread, it must “meet” the scheduler more often.

– When event dispatch thread pauses, the red-ball thread is still sleeping, just as the black-ball thread.

Page 36: java threads

sleep vs. yield• In BallThread, sleep is called to give other thread a chance to run.• Another way is to call yield.

class BallThread extends Thread{ public BallThread(Ball aBall) { b = aBall; }

public void run() // codes for new thread { for (int i = 1; i <= 1000; i++) { b.move(); yield(); // used to be sleep(5) } } private Ball b;}

Page 37: java threads

sleep vs. yield• There is a big difference

– Calling sleep put the current running thread into the blocked state

– Calling yield does not put the calling thread, t1, into the blocked state

• It merely let the scheduler kick in and pick another method to run.

• It might happen that the t1 is select to run again. This happens when t1 has a higher priority than all other runnable threads.

BounceExpress1/BounceExpress.java

Page 38: java threads

Thread Scheduling Cooperating vs. Selfish threads:

A cooperating thread gives others a chance to run Calling sleep: pause for the specified period of time Calling yield: pause temporarily. Scheduler kicks in.

A selfish thread does none of this.

Effects of selfish threads are system-dependent: Green thread: A selfish thread can consume all the CPU time. Native thread: A selfish thread doesn’t post a big problem.

Page 39: java threads

Thread Scheduling• BounceSelfish.java

public void run() { try { for (int i = 1; i <= 1000; i++) { b.move(); if (selfish) { // busy wait for 5 milliseconds long t = System.currentTimeMillis(); while (System.currentTimeMillis() < t + 5 ; } else sleep(5); }} catch (InterruptedException exception){} }

Page 40: java threads

Thread Scheduling

• Question 3:– The balls some times jump.– Why?

– Event dispatch thread does get the time to run. Paint events accumulate.

Page 41: java threads

Outline• Introduction: Why and what• Basics: creating and running threads

• Issues– Thread states– Thread scheduling– Synchronization– Suspending and stopping threads

• Uses– Animation– Threads and Swing

Page 42: java threads

Synchronization• The Synchronization problem:

Two different threads modify the same object at the same time, leading to corrupted object. Such a situation is called race condition.

• An analog:– You and your partner are finishing a group project and starting

to write the project report.– The report is kept at a centralized location.

• You open the report and edit it• Your partner opens the report and edits it• You save the edits.• Your partner saves his edits,

– Your edits are lost!

Page 43: java threads

Synchronization

• An example: UnsynchBankTest.java– class Bank

• A bank with a number of bank accounts.

– class TransferThread extends Thread• A thread that transfers money from an account to other

accounts in a bank.

– public class UnsynchBankTest• Create 10 accounts and multiple threads to make random

transfers

Page 44: java threads

Synchronization

• class Bank

public void transfer(int from, int to, int amount){ if (accounts[from] < amount) return ; accounts[from] -= amount; int tmp = accounts[to];

// added by Instructor so that corruption occurs more easily try { Thread.sleep(1); } catch(InterruptedException e) {}

accounts[to] = tmp + amount;

//test: print out total after every 1000 transactions ntransacts++; if (ntransacts % 1000 == 0) test(); }

Page 45: java threads

Synchronization• class TransferThread extends Thread

class TransferThread extends Thread{ public TransferThread(Bank b, int from, int max) {…} public void run() { try { while (!interrupted()) { int toAccount = (int)(bank.size() * Math.random()); int amount = (int)(maxAmount * Math.random());

bank.transfer(fromAccount, toAccount, amount); sleep(1); }} catch(InterruptedException e) {} } private Bank bank; private int fromAccount; private int maxAmount;

Page 46: java threads

Synchronization• Class UnsynchBankTest

public static void main(String[] args) { Bank b = new Bank(NACCOUNTS, INITIAL_BALANCE); int i; for (i = 0; i < NACCOUNTS; i++) { TransferThread t = new TransferThread(b, i, INITIAL_BALANCE); t.setPriority(Thread.NORM_PRIORITY + i % 2); t.start(); } }

public static final int NACCOUNTS = 10; public static final int INITIAL_BALANCE = 10000;

Note: Total amount in all accounts = 100,000

Page 47: java threads

Synchronization

• Run the program

– Very quickly, the amounts in the accounts do not add up to 100,000

– Why?• The transfer method of Bank class is not atomic:

consists of many steps• Can be interrupted in the middle

Page 48: java threads

Synchronization• Problem scenario:

– Thread 1 • Takes 50 from Account A• Reads current balance of Account B and stores value in variable tmp• Goes to sleep (simulate interruption, self interruption)

– Thread 2 • Deposit some fund to Account B

– Thread 1• Update balance of Account B: tmp + 50

– Result:• Deposit by Thread 2 is lost!

• The total amount can only be less than 100,000

Page 49: java threads

Synchronization

• Note that even instructions are not atomic.

– Consider the following accounts[to] += amount;

– It is processed in three steps as follows:1. Load current value of accounts[to] to a register2. Add amount3. Move the result back to accounts[to].

Page 50: java threads

Synchronization• Execution interruption

accounts[0] is currently 100. Thread 1 perform

accounts[0] += 50; Thread 2 performs accounts[0] += 50; The correct result should be: accounts[0] == 200. What is the result if the following happens?

Actual result: accounts[0] == 150The probability of such interruptions is low (but possible). This

is why we faked interruption using sleep.

Thread 1 Steps 1, 2 Step 3

Thread 2 Steps 1, 2, 3

Page 51: java threads

Synchronization• How to avoid the work of the transfer method being interrupted?

– In java, the answer is to make the method synchronized.

class Bank { … public synchronized void transfer(int from,

int to,int amount) { while (accounts[from] < amount ) {…}

accounts[from] -= amount;

try { Thread.sleep(1); } catch(InterruptedException e) {}

accounts[to] += amount; ntransacts++; if (ntransacts % 1000 == 0) test();}

}// SynchronizedBankTest0.java

Page 52: java threads

Synchronization

• How does the mechanism work?– Object locks

• When a thread calls a synchronized method of an object, the object is locked.

• All other threads that try to call synchronized methods of the object are blocked. – The thread inside the object can of course call all synchronized methods– Threads that call unsynchronized methods of the object can proceed.

• When the thread that locked the object finishes or terminates because of uncaught exception, it relinquishes the object lock

• Periodically, the thread scheduler activates the threads waiting for the lock. They all become runnable.

• When one of the blocked threads is scheduled to run, it checks to see if the object is locked. If not, it proceeds and locks the object.

Page 53: java threads

Synchronization

• In the bank example, if a thread is executing b.transfer(…), it locks the Bank object b.

• While b is locked, other threads trying to call b.transfer(…) are blocked. • b.transfer(…) is not interrupted.

Page 54: java threads

Synchronization

• When the thread that locks b finishes, it gives up the object lock. The “door” is again open.

• Periodically, the thread scheduler unblocks all threads waiting for the object lock

• When such a thread is scheduled to run again, it checks whether b is still locked. If not, it proceeds and locks b.

• Otherwise, it becomes blocked again.

Page 55: java threads

Synchronization• Note that SynchronizedBankTest0.java

is much slower than UnsynchronizedBankTest.java– Other threads trying to get into an bank account cannot do so if it is locked by another thread, even that thread is sleeping inside!

• Synchronization takes time. – Reason why not all methods are synchronized.– In particular, most methods of classes in Swing are not

synchronized.• Swing is not thread-safe.

Page 56: java threads

Synchronization/wait and notify

• What to do when the from account does not have sufficient fund?

– Currently, transfer nonetheless– One possible solution

public synchronized void transfer(int from, int to, int amount)

{ if (accounts[from] < amount) return ;

– Obviously not good solutions.

Page 57: java threads

Synchronization/wait and notify

• How about this?public void synchronized transfer(int from, int to, int amount)

{ while (accounts[from] < amount) { try { Thread.sleep(5); }catch(InterruptedException e) {} }

• The idea is– The balance of the from account might increase after 5 milliseconds

• But does not work:– A sleeping thread does not relinquishes its object locks– In the case, no other threads can get in the bank object and make transfers– Account balances will be the same when the thread wakes up.

Page 58: java threads

Synchronization/wait and notify

• Solution: Call wait instead of sleep.

public synchronized void transfer(int from, int to, int amount)

{ while (accounts[from] < amount) { try { wait(); } catch(InterruptedException e) {} }…}

• How does this work?

Page 59: java threads

Synchronization/wait and notify

wait

notifyAll

Page 60: java threads

Synchronization/wait and notify

• wait is a method of the Object class. It causes the calling method to wait (blocked) until notified (when another thread calls notify or notifyAll)

• While waiting, a thread relinquishes its object locks. This gives other thread a chance to access the object.

• notify or notifyAll are all methods of the Object class. – notify randomly selects a thread among those waiting for an object lock

(inside the object) and unblocks it.

– notifyAll unblocks all threads waiting for an object lock (inside the object). Preferred because it reduces the probability of deadlock (Exercise: Why is this?).

• Note: wait, notify and notifyAll should only be called by a thread that is the owner of this object's monitor (within synchronized method).

Page 61: java threads

Synchronization/wait and notify• In our example, a thread calls notifyAll when it is done with a object.

public synchronized void transfer(int from, int to, int amount)

{ while (accounts[from] < amount) { try { wait(); } catch(InterruptedException e) {} } … notifyAll();

…}SynchBankTest.java

Page 62: java threads

Synchronization/Deadlock Deadlock occurs when a number of threads waiting for

each other

Example:Account 1: $2,000Account 2: $3,000Thread 1: Transfer $3,000 from account 1 to account 2Thread 2: Transfer $4,000 from account 2 to account 1

It is the responsibility of programmer to avoid deadlocks.

Page 63: java threads

Outline• Introduction: Why and what• Basics: creating and running threads

• Issues– Thread states– Thread scheduling– Synchronization– Suspending and stopping threads

• Uses– Animation– Threads and Swing

Page 64: java threads

Stopping and Suspending Threads The stop method is deprecated because it can corrupt

objects.

Consider a thread that is transferring money from one account to another.

If the thread is stopped after withdrawal from the first account and before deposit to the second account, an error arises.

(Other threads can continue since the stopped thread releases all locks.)

Page 65: java threads

How to stop a thread safely?

Introduce variable stopRequested and check it in a safe place of the run method Public class MyThread extends Thread { public void run () { try { while ( !stopRequested && more work to do)

{ do more work} } catch (InterruptedException e) { if (stopRequested ) return;

} } public void requestStop() { stopRequested = true; interrupt();

} private boolean stopRequested = false;}

To terminate a thread t, call t.requestStop();

Page 66: java threads

Why and how does it work: If thread t is running and no more work to do, run method returns

naturally. (Natural death).

If t.requestStop() is called, 1. While t is running. The thread will exit the next time it checks

the condition “!stopRequested”. (It will not stop in the middle of executing a synchronized method and hence does not lead to corrupted objects.)

2. While t is sleeping or blocked. The thread is interrupted, causing an InterruptedException. The exception handler will terminate the thread. To avoid corrupted objects, make sure that a thread doesn’t sleep

while executing a synchronized method. You should never do this anyway.

Waiting is no problem because it gives up object lock)

Stopping and Suspending Threads

Page 67: java threads

Stopping and Suspending Threads The suspend and resume methods are deprecated

because they can easily lead to deadlocks. (Suspended threads do not release object locks.)

Suppose you suspend a thread t1, and t1 has locked an object x.

Further suppose t2 is responsible to resume t1 but it needs to access a synchronized method of x first.

Then, deadlock results.

The resume method is deprecated because suspend is.

Page 68: java threads

How to suspend a thread safely? Use the wait and notifyAll methods

Suspend by calling wait and resume using notifyAll

1. Write a class so that we can use its objects for locks

public class suspenderRequestor{ public synchronized void set (boolean b) { suspendRequested = b; notifyAll();} public synchronized void waiteForResume() throws InterruptedException { while ( suspendRequested) wait (); }

private boolean suspendRequested}

Page 69: java threads

2. Structure your thread class as followspublic class MyThread extends Thread { public void requestSuspend()

{ suspender.set( true ); }

public synchronized void requestResume() { suspender.set(false);} public void run () { while ( more work to do) { suspender.waitForResume();// call this once in a while do more work; } } private SuspendRequestor suspender

= new SuspendRequestor();}

To suspend and resume a thread t, call t.requestSuspend(); t.requestResume();

Page 70: java threads

Stopping and Suspending ThreadsWhy and how does this work? If t.requestSuspend() is called,

suspender.suspendRequest becomes true.

The next time t calls suspender.waitForResume(), t waits inside object suspender.

It will resume only when another thread calls t.requestResume(), which calls suspender.set(true), which in turn notifies t.

While t is waiting, it releases all object locks. This is different from suspend.

Page 71: java threads

Outline• Introduction: Why and what• Basics: creating and running threads

• Issues– Thread states– Thread scheduling– Synchronization– Suspending and stopping threads

• Uses– Animation– Threads and Swing

Page 72: java threads

Animation• Animation: a separate thread to sequentially

display a sequence of images, each of which is called a frame.

• Managing images1. You can put each frame in a separate file, or2. Put all frames on one file. (See right).

We have studied case1 in RunnableTest.java.

For case 2, we have Animation.java.

Page 73: java threads

Animation

• Show one frame of image

public class Animation extends JApplet{ public void loadImage(URL url).. { // size applet to the size of one frame

resize(imageWidth, imageHeight / imageCount);

} public void paint(Graphics g) { if (image == null) return; // put this point at the upper-left // corner of applet g.drawImage(image, 0, -(imageHeight/imageCount) * current, null); }

… Applet

Page 74: java threads

Animation

• Lunching new thread for showing frames

public class Animation extends JApplet{ public void start() { runner = new Thread() { public void run() { try { while (!Thread.interrupted()) { repaint(); current = (current + 1) % imageCount; Thread.sleep(200); } } catch(InterruptedException e) {} }}; runner.start(); showStatus("Click to stop"); }

Page 75: java threads

Outline• Introduction: Why and what• Basics: creating and running threads

• Issues– Thread states– Thread scheduling– Synchronization– Suspending and stopping threads

• Uses– Animation– Threads and Swing

Page 76: java threads

Threads and Swing Threads in a Swing program:

Main thread: started by main method and usually exits after displaying frame window.

Event dispatch thread: started when the first window is shown and stays alive until terminated by user.

Event dispatch thread runs codes for handling events such as calls to actionPerformed or paintComponent.

Page 77: java threads

Threads and Swing From the event dispatch thread, one wants to fire

up threads for

Time-consuming actions Actions that can be blocked on I/O Sleeping

Otherwise, GUI might seem dead or frozen.

Page 78: java threads

Threads and Swing Caution: Swing is not thread safe!

Most methods in Swing classes are not synchronized. If one tamper with UI components from different threads, UI

might be corrupted.

Single thread rule for Swing programming Modify UI components only in the event dispatch thread

Other threads should send actions that modify UI components to the event dispatch thread using the invokeLater or invokeAndWait methods of the EventQueue class (see textbook for details.)//swingThreadTest.java

Page 79: java threads

Summary of classes and methods• public class Thread extends Object implements Runnable

– Thread() , Thread(Runnable target) – Constants: MAX_PRIORITY NORMAL_PRIORITY, MIN_PRIORITY– static: sleep, yield, interrupted– start, run, setPriority, setPriority, interrupt– isAlive, isInterrupted

• public interface Runnable– run

• public class Object– wait, notify, notifyAll

• public class InterruptedException extends Exception


Recommended