concurrent programming and threads threads blocking a user interface

Post on 13-Jan-2016

239 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Concurrent Programming and Threads

Threads

Blocking a User Interface

Concurrent Programming

• concurrent = in parallel or at the same time• Concurrent programming

– multiple operations can be performed at the same time

– Only computers with multiple processors can execute operations concurrently

– Single processor computers ‘simulate’ concurrency

– (Not be mixed up with concurrency in databases)• Java provides multithreading as part of the

language– facilitates concurrent programming

Multithreading

• Application = multiple threads

• Portion of the application assigned to each thread

• Threads may run concurrently– each gets a time slice of CPU time

• Example: Java’s garbage collector

Multithreading

Task 1

Task 2

Tasks3

Application

Single Threaded Application

CPU time

Multi-Threaded Application

CPU time

In a Java application…

main Almost all code executes in the main thread

event For GUI applications an event thread is also createdand runs in parallel with main thread

Event thread uses an event fifo queue. Processing an event means calling the appropriateevent handler.events

mouseclick

buttonpress

paintmenu item select

buttonpress

Blocking a user interface

• JFrame Window – single JLabel (msg) in content pane– “Start” menu item – menu item event handler performs a lengthy job

• loops 10 times• sleeps for a second inside each loop• text of msg label is updated in each loop• output also sent to console

Display some text here..

Menu

// set up content pane with single label private JPanel createContentPane(){ // set up the message label with “Display text here” etc }

// set up menu private JMenuBar createMenuBar(){ JMenuBar bar = new JMenuBar(); JMenu menu = new JMenu("Menu");

// set up the “start” menu item // and assign the listener etc

Etc }

// event handler for menu item public void actionPerformed(ActionEvent e) {

//set up the message test to appear on the screen to say “starting..”

// initiate some “slow “processing }

JFrame class

// Method to perform work that takes a while private void performLengthyWork() {

{

// set up “slow” loop processing and get thread to sleep.. Printing out a message on each loop both to the console AND to the screen

} msg.setText("Done...."); }

Expect to see?

Display some text here..

Starting…

Working1Working2 etc.. done

But actually…

Display some text here..

Done

StartMenu

Menu

GUI Blocked for 5 seconds… then

(The Console updates though…)

Console

Running in thread main

Working 0

Running in thread AWT-Event Querue-0

Working 2

Running in thread AWT-Event Querue-0

Working 3

Running in thread AWT-Event Querue-0

• etc

Blocking Window

• All code is executing on the event thread so has to wait until the “menu item select” event has finished

Select “Start”

Paintopenedmenu

Click on “Menu””

paintmenu

paintlabel

paintlabel

invokes the actionPerformed method

which performs the lengthy processing

But the “paint” method to redraw the screen with the retracted menu goes next..So open menu is left on the screen waiting for Lengthy

work to finish..

Paintclosedmenu

Repaintlabel

Repaintlabel

Blocking window

• When menu is clicked, command to repaint the GUI with the opened out menu added to event queue. – Repaint executes .. And menu item “start” appears

• When menu item Start selected – call to Action Performed is added to event queue

• Command to redraw the GUI with the closed menu is added to the queue behind the call to action Performed ..

• For each “for” loop, a command to draw the label with updated text is added to the queue behind the repaint command…

Non Blocking Window

• Put lengthy processing in a separate thread

Clickon

“Menu”

paintmenu

Select“Start”

paintmenu

paintlabel

paintlabel

starts a new Thread runningto perform lengthy processing –

no need to wait till it finishes

Thread Class

• useful instance methods– start() – starts the execution of the thread,

must be invoked to get the thread running– run() – contains the executable code of the thread

• useful static method– sleep(int time) – causes thread to suspend

execution for a specified period of time

Non Blocking Window

• Put lengthy processing in a separate threadso it no longer blocks the event thread which contains the various repaints..

• Thread code often done as an inner class (but doesn’t have to be..)

• Java has a Thread class.. – Start () method has to be called to get it running– Run() method has to be filled up with whatever it is

supposed to do..

• In our example.. performLengthWork will go in the thread..

Non Blocking Window

// inner class - new thread to perform the lengthy work

// As displayed in class..

Subclass the Thread class..

And get this class to perform the “slow” work..

}

• Make your own thread class..

• Constructor optional…

• Run() method

Non Blocking Window

// event handler for menu item public void actionPerformed(ActionEvent e) { msg.setText("Starting..."); // Instantiate your own thread class, and start it.

.. etc}

private void performLengthyWork(){ Etc

} }

• Instantiate thread

• Start it..!

Now you’ll see..

Display some text here..

Starting…

Working1Working2 etc.. done

Non blocking window

• Start menu item clicked:Actionperformed – Creates the worker thread and starts it..– BUT it doesn’t generate changes to the GUI– Finishes..

• Menu is retracted..

• Follow on repaint label processed on the event thread…

Worker Thread is separate from event thread.. No longer blocking event thread…

Note: Other way to implement threading

• Used Thread class – and extended it..

• Can also use runnable interface.. Contains a run() method..– Create a class e.g. myThread that implement

runnable, and contains the run() method– When you need a threat, instantiate the class, and

pass to new Thread(myThread)

Threads..

• Good for splitting processing to let things happen in the background

• Instiantiate Thread class or use Runnable interface

• Use run() method for what thread should do and start() method to kick it off..

top related