• Nie Znaleziono Wyników

1 Szeregowanie rotacyjnePrzeplot czasowy Przetwarzanie równoległe i współbieŜneCechy programowania wątkowego Wątki (Threads) Potrzeby

N/A
N/A
Protected

Academic year: 2021

Share "1 Szeregowanie rotacyjnePrzeplot czasowy Przetwarzanie równoległe i współbieŜneCechy programowania wątkowego Wątki (Threads) Potrzeby"

Copied!
6
0
0

Pełen tekst

(1)

Wątki (Threads)

• Concurrent programming is like stepping into an entirely new world and learning a new programming language!!! (grząski grunt)

• Unikaj jeśli moŜesz!

• Oparte są zwykle na wielozadaniowym SO (dlatego brak JVM dla DOS, w3.1)

Potrzeby

• One of the most compelling reasons for concurrency is to produce a responsive user interface.

• Twój program realizuje eksperyment, masz na GUI przycisk <quit> ? Sprawdzasz jego stan co pewien odcinek czasu?

Przetwarzanie równoległe i

współbieŜne Cechy programowania wątkowego

• „Zachowanie” wątków jest zaleŜne od platformy

• program wielowątkowy moŜe być wolniejszy!

• W Javie mamy 10 poziomów priorytetu (Solaris 2

31

, NT 7)

• Thread.MAX_PRIORITY, Thread.NORM_PRIORITY, Thread.MIN_PRIORITY

• A thread can be preempted at any time by another thread

Szeregowanie rotacyjne Przeplot czasowy

(2)

Klasa Thread

• Klasa Thread nie jest wątkiem!

• Klasa moŜe być kontrolerem wątku

• Z faktu Ŝe zdefiniujemy jakąś metodę w klasie pochodnej od Thread nie oznacza, Ŝe działa ona w osobnym wątku !

Thread c.d.

• start( ) //special initialization

• and then calls run( ).

• output for one run of this program will be different from that of another !!!

• thread scheduling mechanism is not deterministic !

Pierwszy sposób

class simpleThread extends Thread { public SimpleThread (String s) {

super(s) ; } public void run() { for (int i=0; i<10; i++) {

System.out.println(i+ getName()); } }

} }

Przykład wykorzystania

class ThreeThreads { ...

main(String[] args) {

new SimpleThread(”Pierwszy”).start() ; new SimpleThread(”Drugi”).start() ; new SimpleThread(”Trzeci”).start() ; }

}

2 sposób Interfejs Runnable

Obiekt, który chce być kontrolerem wątku (określać co wątek ma robić) powinien wskazać Ŝe dysponuje odpowiednią metodą

„wykonawczą” deklarując implementację interfejsu Runnable w którym zdefiniowano metodę:

public interface Runnable { abstract public void run();

}

Obiekty klas implementujących interfejs Runnable moŜemy określić jako „wykonywalne” (aktywne) gdyŜ mogą być podstawą do uruchomienia wątku

KaŜdy obiekt moŜe być kontrolerem wątku (klasa moŜe implementować dowolna liczbę interfejsów)

Przykład

class Animation implements Runnable { ...

public void run() { while ( true ) {

// Draw Frames ...

repaint();

} } }

Animation happy = new Animation("Mr. Happy");

Thread myThread = new Thread( happy );

myThread.start();

...

(3)

Przykład Usypianie wątku

try {

Thread.sleep ( 1000 );

}

catch ( InterruptedException e ) { }

Zakończenie wątku

Wątek kończy działanie gdy wystąpi jeden z trzech przypadków:

• returns from its target run() method

• interrupted by an uncaught exception

• before Java 1.2 its stop() method is called public final void stop()

Deprecated. This method is inherently unsafe.

run()

public void run() { while(true) {

System.out.println(this);

if(--countDown == 0) return;

try { sleep(100); }

catch (InterruptedException e) { throw new RuntimeException(e); } }

Thread states

NEW

A thread that has not yet started is in this state.

RUNNABLE

A thread executing in the Java virtual machine is in this state.

BLOCKED

A thread that is blocked waiting for a monitor lock is in this state.

WAITING

A thread that is waiting indefinitely for another thread to perform a particular action is in this state.

TIMED_WAITING

A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state.

TERMINATED

A thread that has exited is in this state.

Synchronizacja wątków

Synchronizacja wątków w języka Java bazuje na koncepcji monitorów opracowanej przez C.A.R. Hoare. Monitor spełnia rolę zamka związanego z współuŜytkowanym zasobem. Jeśli zasób jest wolny obejmujesz go (drzwi otwarte – wchodzisz i zamykasz). Po zakończeniu uŜywania zwalniasz (otwierasz, wychodzisz następna osoba moŜe skorzystać). Jeśli zasób jest zajęty wątek musi czekać.

Monitory związane są z obiektami .

Słowo kluczowe synchronized słuŜy do oznaczenia miejsca, w którym wątek musi objąć monitor. Oznaczona tym słowem aktywność wykonuje się niepodzielnie*

(4)

Metody synchronizowane

class SpreadSheet { int cellA1, cellA2, cellA3;

synchronized int sumRow() { return cellA1 + cellA2 + cellA3;

}

synchronized void setRow( int a1, int a2, int a3 ) { cellA1 = a1; cellA2 = a2; cellA3 = a3;

} ...

}

Synchronizowany blok

synchronized ( myObject ) {

// Functionality that needs to be synced ...

}

synchronized void myMethod () { ... }

is equivalent to:

void myMethod () { synchronized ( this ) { ... }

}

wait() notify()

By executing wait() from a synchronized block, a thread gives up its hold on the lock and goes to sleep. A thread might do this if it needs to wait for something to happen in another part of the application. Later, when the necessary event happens, the thread that is running it calls notify() from a block synchronized on the same object. Now the first thread wakes up and begins trying to acquire the lock again.

Problem Producent - konsument

class Producer extends Thread { static final int MAXQUEUE = 5;

private Vector messages = new Vector();

public void run() { try {

while ( true ) { putMessage();

sleep( 1000 );

}

} catch( InterruptedException e ) { } }

...

}

Konsument

class Consumer extends Thread { ...

public void run() { try {

while ( true ) {

String message = producer.getMessage();

System.out.println("Got message: " + message);

sleep( 2000 );

}

} catch( InterruptedException e ) { } }

}

putMessage()

private synchronized void putMessage() throws InterruptedException {

while ( messages.size() == MAXQUEUE ) wait();

messages.addElement( new java.util.Date().toString() );

notify();

}

(5)

getMessage()

// Called by Consumer

public synchronized String getMessage() throws InterruptedException {

notify();

while ( messages.size() == 0 ) wait();

String message = (String)messages.firstElement();

messages.removeElement( message );

return message;

}

???

• Gdzie powinny być umieszczone metody getMessage() i putMessage()

Wątki w komponencie

public class Kompas extends Component implements Runnable { ...

Int azymut, newAzymut ; Thread compasThread ;

public Kompas(int azymut) { // konstruktor this.azymut = this.newAzymut = azymut ; compasThread = new Thread(this);

compasThread.start();

} //end of constructor }

Metoda run()

public void run () { while(true) {

if (newAzymut != azymut ) { try {

Thread.currentThread().sleep(100);

} catch (InterruptedException e) { // obsługa błędu } azymut++; azymut %=360;

repaint();

} } //end of while }

Setter

public void setAzymut (int newAzymut) { this.newAzymut = newAzymut;

// repaint(); Thread does it instead }

Źródło impulsów

public class PulseGenerator extends Thread implements PulseSource

byte mode ; boolean on ; ...

public PulseGenerator() {

mode = PulseSource.BURST_MODE ; start() ;

}

(6)

Źródło impulsów

public void run() { while (on) {

// fire up pulse event

// test mode & check if last pulse // sleep for a moment

} }

public void halt() { on = false ;}

public void trigger() { ???}

Cytaty

Powiązane dokumenty

Uzupełniono kod metody equals, która przesłania metodę equals dziedziczoną od klasy Object.. Java Zofia

Uruchom aplikację (Kliknij prawym klawiszem myszy w oknie Project na nazwę projektu, w ukazanym oknie uruchom kolejno Build Project, Deploy Project,

Uruchom aplikację (Kliknij prawym klawiszem myszy w oknie Project na nazwę projektu, w ukazanym oknie uruchom kolejno Build Project, Deploy Project, Run Project lub tylko Run

[r]

[r]

[r]

[r]

[r]