10.07.2015 Views

Thread - schmiedecke.info

Thread - schmiedecke.info

Thread - schmiedecke.info

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

What are Objects like so far? They offer Services:- Reading an number from the console- Storing data- Keeping an account status An interface often serves as users‘ instructions for ausing class:Using Class Interface Service Classknowsimplements Objects are passive, they only work when called upon- readNumber(), transferSum()(c)<strong>schmiedecke</strong> 06 Inf1-7a: Animation 2


Active Objects• Balls in BallWorld behave differently• They do react to impulses (clicking), but they alsowork without outer impulse.• The general situation is similar,BallWorld Ball Exploderknowsimplements• but Ball Objects behave differently.(c)<strong>schmiedecke</strong> 06 Inf1-7a: Animation 3


How does Object Activity Happen?ModellCall-Center• Prozedurales Functional concept: Modell:nur objects scheinbar seem active, aktive Objekte,• reagieren react to stimuli nur auf of aAnfrage calling (durch process einen rufenden• Prozess) BallWorld calls the act() method of all ist Ball objects• in Ballworld an indefinte ruft in loop einer Endlosschleife immer wiederact()ModellService• OO concept:objects are independant, interacting units• act independantly (also react to stimuli)• Every Ball object has its own process which indefinitelycalls its act() method(c)<strong>schmiedecke</strong> 06 Inf1-7a: Animation 4


Counter and Timer(c)<strong>schmiedecke</strong> 06 Inf1-7a: Animation 5


Common Interfacepublic interface Incrementor {}public void increment();public void reset();public int getValue();public class Counter implements Incrementor {protected int value = 0;public void increment() { value++; }public void reset() { value = 0; }public int getValue() { return value; }}public class Timer extends Counter implements Animate {public void act() { increment(); }} Only(c)<strong>schmiedecke</strong> 06 Inf1-7a: Animation difference 6


... who calls act()?Processes and <strong>Thread</strong>sA process is an instruction follower which is started andcontrolled by the operating system.An instruction follower which is started and controlled withina process is called a <strong>Thread</strong> ("Lebens-Faden").In Java, threads are instances of <strong>Thread</strong> .A <strong>Thread</strong> object can be started.Once started, it is "alive" and can animate otherobjects (e.g. call act()).(c)<strong>schmiedecke</strong> 06 Inf1-7a: Animation 7


Animator<strong>Thread</strong> animates Timeract!Animator<strong>Thread</strong>instance(has its own <strong>Thread</strong>)"animates" passive objectof type Animate(without a <strong>Thread</strong>)(c)<strong>schmiedecke</strong> 06 Inf1-7a: Animation 8


Animator<strong>Thread</strong> animates Ballact!ExploderAnimator<strong>Thread</strong>instance(has its own <strong>Thread</strong>)"animates" passive objectof type Animate(without a <strong>Thread</strong>)(c)<strong>schmiedecke</strong> 06 Inf1-7a: Animation 9


The Animator<strong>Thread</strong> ClassAnimator<strong>Thread</strong>knowsAnimateimplementsAnimatedObject Every instance of Animator<strong>Thread</strong> possesses its own thread. Its constructor attaches it to a (passive) Animate object which itanimates. Once started, it calls the Aminate's act() method indefinitely.Animate timer = new Timer();Animator<strong>Thread</strong> timer<strong>Thread</strong> = new Animator<strong>Thread</strong>(timer);timer<strong>Thread</strong>.startExecution();Animate :timer xBall = new Exploder();Animator<strong>Thread</strong>Animate:timertimer<strong>Thread</strong> = new Animator<strong>Thread</strong>(xBall);timer<strong>Thread</strong>.startExecution();kenntimplementiert(c)<strong>schmiedecke</strong> 06 Inf1-7a: Animation 10


package cs101.lang;Animator<strong>Thread</strong> Servicespublic class Animator<strong>Thread</strong> extends <strong>Thread</strong> {public Animator<strong>Thread</strong>(Animate animatedObject);public void startExecution(); //indefinite looppublic void stopExecution (); //for goodpublic void suspendExecution (); //temporarilypublic void resumeExecution (); //following suspend}public void setSleepMinInterval(long millis);public void setSleepRange(long millis);(c)<strong>schmiedecke</strong> 06 Inf1-7a: Animation 11


Set Alivepublic class BallWorld extends World{// ...// method is called when button is pressedpublic void startExploder() {// create and launch ballExploder xBall = new Exploder();this.addBall(xBall);}// animate ballAnimator<strong>Thread</strong> expl<strong>Thread</strong> =new Animator<strong>Thread</strong>(xBall);expl<strong>Thread</strong>.startExecution();}//...(c)<strong>schmiedecke</strong> 06 Inf1-7a: Animation 12


Create Aliveclass Throbber implements Ball, Animate {World world;// Animation in the constructorpublic Throbber(World world) {this(); // initialize x, y, radiusthis.world = world;}// create and grasp your own threadAnimator<strong>Thread</strong> throb<strong>Thread</strong> =new Animator<strong>Thread</strong>(this);throb<strong>Thread</strong>.startExecution();}public void act() { // called by expl<strong>Thread</strong>}//...(c)<strong>schmiedecke</strong> 06 Inf1-7a: Animation 13


Active Timerpublic class Timer extends Counter implementsAnimate {private Animator<strong>Thread</strong> timer<strong>Thread</strong>;public Timer () {timer<strong>Thread</strong> = new Animator<strong>Thread</strong>(this);timer<strong>Thread</strong>.startExecution();}}public void act() {increment();}(c)<strong>schmiedecke</strong> 06 Inf1-7a: Animation 14


Delayed Startpublic class Timer extends Counter implementsAnimate {private Animator<strong>Thread</strong> timer<strong>Thread</strong>;}public Timer () {timer<strong>Thread</strong> = new Animator<strong>Thread</strong>(this);}public void init() {timer<strong>Thread</strong>.startExecution();}public void act() {increment();}Use init() formethods thatare called onlyonce for setup.(c)<strong>schmiedecke</strong> 06 Inf1-7a: Animation 15


Now put it all into the GUI:public class VisibleTimer extends Timer {private AnimationGUI gui;public VisibleTimer(AnimationGUI gui){super();this.gui = gui;}public void increment() {super.increment();gui.updateTimer(value); // shows value in GUI}}public void reset() {super.reset();gui.updateTimer(0); // shows 0 in GUI}(c)<strong>schmiedecke</strong> 06 Inf1-7a: Animation 16


The AnimationGUI Class(for the curious only...) paints the graphical user interface instantiates VisibleCounter and VisibleTimerYou can download AnimationGui,everything else is up to you towrite. calls on button action their methods increment() undreset() defines two output methods, updateCounter() andupdateTimer(), which are called by VisibleCounter andVisibleTimer on every increment() or reset(). The buttons "pause" and "cont." are used to call two Timermethods, pause() and continue(), which have not yetbeen implemented (your job ) (Hint: It is common practice to put the main method into the GUIclass)(c)<strong>schmiedecke</strong> 06 Inf1-7a: Animation 17


Observing an Object(two active objects involved)public class CountingMonitor implements Animate {private Counter whoToMonitor;private Animator<strong>Thread</strong> mover;public CountingMonitor(Counter whoToMonitor ) {this.whoToMonitor = whoToMonitor;}this.mover = new Animator<strong>Thread</strong>( this );this.mover.startExecution();public void act(){ Console.println( "The timer says " +whoToMonitor.getValue() );}Gets to know itsobject in theconstructorTry it!}Timer timer = new Timer(); // live creationCountingMonitor monitor = new CountingMonitor(timer);(c)<strong>schmiedecke</strong> 06 Inf1-7a: Animation 18


How Many <strong>Thread</strong>s Can You Get? Any number. An object can – when it's method is executed- create any number of new threads. Result: Tree structure of running threads.(c)<strong>schmiedecke</strong> 06 Inf1-7a: Animation 19


Java Standard <strong>Thread</strong>spackage java.lang;Interface Runnable{ public void run(); } // c.f. Animatepublic class <strong>Thread</strong> { // c.f. Animator<strong>Thread</strong>public <strong>Thread</strong>(Runnable runnerObject);public void start();public boolean isAlive();public void interrupt();public void join();}static void sleep(long millis)throws InterruptedException;static void yield();// ...(c)<strong>schmiedecke</strong> 06 Inf1-7a: Animation 20


<strong>Thread</strong> vs. Animator<strong>Thread</strong> Similar concept:so, if you can use Animator<strong>Thread</strong>, you can work with <strong>Thread</strong> as well. The animated Object must implement Runnable, rather thanAnimateRunnable ticker; // has a run() method<strong>Thread</strong> tickerthread = new <strong>Thread</strong>(ticker);ticker<strong>Thread</strong>.start(); // calls run() ONLY ONCE <strong>Thread</strong> has NO indefinite loop –if wanted, implement it inside the run() method. <strong>Thread</strong>'s methods suspend, resume and stop are not quite safe(supposedly mended in Java5) <strong>Thread</strong> has an unfair scheduler.(c)<strong>schmiedecke</strong> 06 Inf1-7a: Animation 21


Understanding Programm StartThe operating system starts the virtualmachine ProcessThe virtual machine starts a new<strong>Thread</strong>, in which it calls the mainmethodApplets too are run as VM threads.(c)<strong>schmiedecke</strong> 06 Inf1-7a: Animation 22


! "#$ % "!&&&

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!