Multithreaded applets Java threading Multithreaded applets Peter Mozelius DSV/UCSC
Robustness An applet should not crash and hang the browser A program should handle its errors Built in error handling in Java try catch finally
Catching exceptions try – catch - finally try { Do something useful that sometimes can go wrong and throw an Exception; } catch(Exception e) { Here will the exeption be caught; finally { Will always be executed;
Threading A technique for dividing the execution of an applet in parallel tasks As when several instruments play in parallel in an orchestra With synchronized interaction and pauses between the threads
Threading Parallel code execution Multitasking Multithreading To run several processes in parallel Multithreading To run several threads in parallel
Java threads Thread = lightweight process Since the very first ver 1.0 in Java To save system resources Instead of starting a new process Start a new thread Thread = lightweight process
Why threading? For practical and economical reasons Example: A web browser could fetch several images in parallell An applet could show an animations in separate threads, at the same time as the main thread will handle the GUI
How to make threads sleep So other threads should be able to execute their tasks the thread must sometime sleep for a while We will now look at how you should make threads rest Do we need to rest as well?
How threads sleep Threads will be put in bed by sleep() As an argument this method will need the number of milliseconds to sleep Example: sleep(1000); Makes the thread sleep exactly 1 second
Exception handling To avoid thread trouble: try{ sleep(millisec); }catch(InterruptedException ie){ System.out.print(”Thread error: ”); System.out.print(ie.getMessage()); }
Starting and stopping threads If you create a thread like: Thread t = new Thread(); You’ll later start it by: t.start();
Starting and stopping threads In the class Thread there is also a method named stop() BUT do NOT stop the thread by stop() This method is deprecated because it leaves the thread in an unclear condition
suspend() och resume() Two other ways of stopping and restarting threads are by: suspend() och resume() BUT these methods are deprecated as well because they create deadlocks And they are NOT recommended
How the threads work Threads execute their tasks in run() If the iteration in a run-method is trigged by a boolean condition in a loop The thread will always be able to finish it’s work in a secure manner
A stop condition in run() Create a boolean condition like: private boolean stopped; public void run(){ while(!stopped) { moveTheBall(); }
Thread and Runnable The two ways of creating threads in Java: By subclassing Thread OneClass extends Thread By implementing Runnable AnotherClass implements Runnable
Runnable The fact that Runnable is an interface can be very useful when a class inherits something else like in: MyClass extends JApplet implements Runnable We will now look at some code but first: 15 min PAUS!
Let’s have a break!
Threading with Thread class TestThread extends Thread { private String name; private int sleepTime; public TestThread(String name, int sleepTime) { this.name = name; this.sleepTime = sleepTime; }
Threading with Thread System.out.println("Hello, from : " + name); public void run() { System.out.println("Hello, from : " + name); try { sleep(sleepTime); }catch (InterruptedException ie) { System.err.println(“ERROR in " + name); System.err.println(ie.getMessage()); } System.out.println("Hello again, from: " + name); }//run }//TestThread
Threading with Thread Threads can then be created from an application: (or an applet) public class L4_example1 { public static void main(String[] args) { TestThread t1 = new TestThread(“T1", 2000); TestThread b2 = new TestThread(“T2", 20); t1.start(); t2.start(); } }//L4_example1
Threading with Runnable class MyThread implements Runnable { private String threadName; private int sleepTime; private Thread t; public MyThread(String name, int time) { threadName = name; sleepTime = time; t = new Thread(this); }
Threading with Runnable public void run() { System.out.println("Hello, from: " + name); int i = 0; while (i++ < 2) { try { t.sleep(sleepTime); } catch (InterruptedException ie) { System.err.println(“ERROR in " + name); System.err.println(ie.getMessage());
Threading with Runnable System.out.println("Hello again, from: " + threadName); }//while }//run public void startMe() { t.start(); } }//MyThread
Threading with Runnable public class L4_example2 { public static void main(String[] args) { MyThread t1 = new MyThread("T1", 2000); MyThread t2 = new MyThread("T2", 20); t1.startMe(); t2.startMe(); } }//L4_example2
Graphics in threaded classes If two diffrent thread classes want to write to the same graphical component:
Graphics in threaded classes A reference to the graphical component can be passed to the constructor in the thread class : class PenThread extends Thread { private JPanel centerPanel ; public PenThread(JPanel centerPanel) { this.centerPanel = centerPanel; ...
Graphics in threaded classes Then you can write on the panel by: public void write() { Graphics pen = centerPanel.getGraphics(); pen.drawString("Hello, from: " + threadName, x, y); pen.dispose(); }
Graphics in threaded classes The complete code for L4_example3 can be found in the Moodle system An example that could be a good start for solving Assignment 7 So let’s run this applet!