Lab13.pdf

(132 KB) Pobierz
Programowanie obiektowe /Java/
Laboratorium nr 13
Uwaga !!! Wyniki uruchomionych programów mogą zależeć od sprzętu (ilość procesorów, rdzeni itp.),
systemu operacyjnego i jego obciążenia, ilości wątków w programie (zmienna SIZE), itp.
1
Wątki
Interfejs
Runnable
1
:
public void run()
– metoda, która ma się wykonywać współbieżnie.
W celu uruchomienia nowego wątku należy w wybranej klasie zaimplementować interfejs
Runnable.
Na-
stępnie jako parametr konstruktora klasy
T hread
należy przekazać obiekt klasy implementującej ten interfejs,
a następnie dla utworzonego wątku należy wywołać metodę
start().
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package
pl.kielce.tu.lab13;
import
java.util.concurrent.TimeUnit;
public class
TestRunnable
implements
Runnable {
private int
t;
public
TestRunnable(int t) {
this.t
= t;
}
public void
run() {
for
(int i = 0; i < 20; i++) {
System.out.println(this);
try
{
TimeUnit.MILLISECONDS.sleep(t);
// lub Thread.sleep(t);
}
catch
(InterruptedException e) {
e.printStackTrace();
}
}
}
public static void
main(String[] args) {
Thread t1 =
new
Thread(new TestRunnable(1000));
t1.start();
Thread t2 =
new
Thread(new TestRunnable(10000));
t2.start();
}
}
Przykład 1: src/pl/kielce/tu/lab13/TestRunnable.java
{link}
Klasa
T hread
W celu stworzenia nowego wątku w klasie dziedziczącej po
T hread
należy przesłonić metodę
run(),
a następnie
dla wątku wywołać metodę
start().
1
2
3
4
5
6
7
package
pl.kielce.tu.lab13;
import
java.util.concurrent.TimeUnit;
public class
TestThread
extends
Thread {
private int
t;
1
Thinking
in Java, Bruce Eckel, Wydanie IV, Helion, 2006
1
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public
TestThread(int t) {
this.t
= t;
}
@Override
public void
run() {
for
(int i = 0; i < 20; i++) {
System.out.println(this);
try
{
TimeUnit.MILLISECONDS.sleep(t);
}
catch
(InterruptedException e) {
e.printStackTrace();
}
}
}
public static void
main(String[] args) {
TestThread t1 =
new
TestThread(1000);
t1.start();
TestThread t2 =
new
TestThread(10000);
t2.start();
}
}
Przykład 2: src/pl/kielce/tu/lab13/TestThread.java
{link}
Wybrane metody klasy Thread:
-
public void run()
– metoda, która ma się wykonywać współbieżnie,
-
public void start()
– rozpoczyna wykonywanie nowego wątku,
-
public void join() throws InterruptedException
– oczekuje na zakończenie się wątku,
-
public void interrupt()
– przerywa działanie wątku,
-
public final boolean isAlive()
– sprawdza czy wątek się zakończył,
-
public final boolean isDaemon()
– sprawdza czy wątek jest wątkiem działającym w tle.
Proszę porównać działanie poniższego programu:
- z komentarzami,
- z jednym (dowolnym) komentarzem,
- bez komentarzy?
1
2
3
4
5
6
7
8
9
10
11
12
13
package
pl.kielce.tu.lab13;
public class
TestThreadDaemon
extends
Thread {
public static void
main(String[] args) {
TestThread t1 =
new
TestThread(1000);
// t1.setDaemon(true);
t1.start();
TestThread t2 =
new
TestThread(10000);
// t2.setDaemon(true);
t2.start();
}
}
Przykład 3: src/pl/kielce/tu/lab13/TestThreadDaemon.java
{link}
2
-
public final boolean isInterrupted()
– sprawdza czy działanie wątku zostało przerwane,
-
public static void sleep(long millis) throws InterruptedException
– usypia aktualny wątek na podany
czas,
-
public final void yield()
– wstrzymuje wykonanie aktualnego wątku umożliwiając wykonywanie się innych
wątków,
-
public final void setPriority(int newPriority)
– ustawia priorytet wątku,
-
public final int getPriority()
– pobiera priorytet wątku.
„Unikaj modyfikacji priorytetów wątków
2
, gdyż zwiększają zależność od platformy i stwarzają problemy
z żywotnością.”
W Javie 1.5 dodano pakiet
java.util.concurrent.
Od Javy 1.5 zalecaną metodą uruchamiania wątków jest
metoda wykorzystująca klasy z tego pakietu (Executors).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package
pl.kielce.tu.lab13;
import
java.util.concurrent.ExecutorService;
import
java.util.concurrent.Executors;
import
java.util.concurrent.TimeUnit;
public class
TestCachedThreadPool
implements
Runnable {
private int
t;
public
TestCachedThreadPool(int t) {
this.t
= t;
}
public void
run() {
for
(int i = 0; i < 20; i++) {
System.out.println(this);
try
{
TimeUnit.MILLISECONDS.sleep(t);
}
catch
(InterruptedException e) {
e.printStackTrace();
}
}
}
public static void
main(String[] args) {
Thread t1 =
new
Thread(new TestCachedThreadPool(1000));
Thread t2 =
new
Thread(new TestCachedThreadPool(10000));
ExecutorService e = Executors.newCachedThreadPool();
e.execute(t1);
e.execute(t2);
e.shutdown();
}
}
Przykład 4: src/pl/kielce/tu/lab13/TestCachedThreadPool.java
{link}
1
2
3
4
5
6
package
pl.kielce.tu.lab13;
import
java.util.concurrent.ExecutorService;
import
java.util.concurrent.Executors;
import
java.util.concurrent.TimeUnit;
2
Goetz
B., Peierls T., Bloch J., Bowbeer J., Holmes D., Lea D., Java Współbieżność dla praktyków, Helion 2007
3
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public class
TestFixedThreadPool
implements
Runnable {
private int
t;
public
TestFixedThreadPool(int t) {
this.t
= t;
}
public void
run() {
for
(int i = 0; i < 20; i++) {
System.out.println(this);
try
{
TimeUnit.MILLISECONDS.sleep(t);
}
catch
(InterruptedException e) {
e.printStackTrace();
}
}
}
public static void
main(String[] args) {
Thread t1 =
new
Thread(new TestFixedThreadPool(1000));
Thread t2 =
new
Thread(new TestFixedThreadPool(10000));
ExecutorService e = Executors.newCachedThreadPool();
e.execute(t1);
e.execute(t2);
e.shutdown();
}
}
Przykład 5: src/pl/kielce/tu/lab13/TestFixedThreadPool.java
{link}
2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
Uruchamianie programów
package
pl.kielce.tu.lab13;
import
java.io.BufferedReader;
import
java.io.IOException;
import
java.io.InputStreamReader;
public class
TestProcess {
public static void
main(String[] args)
throws
IOException,
InterruptedException {
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("ipconfig
/all");
BufferedReader input =
new
BufferedReader(new InputStreamReader(
process.getInputStream()));
String s =
null;
while
((s = input.readLine()) !=
null)
{
if
(s.length() > 0) {
s = s.replace(’.’,
’_’);
s = s.replace(’:’,
’_’);
s = s.replace(’
’, ’_’);
System.out.println(s);
}
}
input.close();
process.waitFor();
Process process2 = runtime.exec("notepad");
process2.waitFor();
4
27
28
29
System.out.println("end");
}
}
Przykład 6: src/pl/kielce/tu/lab13/TestProcess.java
{link}
Od wersji Javy 1.5 metoda ProcessBulider.start() jest zalecaną metodą tworzenia procesów.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package
pl.kielce.tu.lab13;
import
import
import
import
java.io.BufferedReader;
java.io.File;
java.io.IOException;
java.io.InputStreamReader;
public class
TestProcessBuilder {
public static void
main(String[] args)
throws
IOException,
InterruptedException {
ProcessBuilder processBuilder =
new
ProcessBuilder(
"C:\\WINDOWS\\system32\\ipconfig", "/all");
processBuilder.directory(new File("C:\\"));
Process process = processBuilder.start();
BufferedReader input =
new
BufferedReader(new InputStreamReader(
process.getInputStream()));
String s =
null;
while
((s = input.readLine()) !=
null)
{
if
(s.length() > 0) {
s = s.replace(’.’,
’_’);
s = s.replace(’:’,
’_’);
s = s.replace(’
’, ’_’);
System.out.println(s);
}
}
input.close();
process.waitFor();
ProcessBuilder processBuilder2 =
new
ProcessBuilder(
"C:\\WINDOWS\\notepad");
Process process2 = processBuilder2.start();
process2.waitFor();
System.out.println("end");
}
}
Przykład 7: src/pl/kielce/tu/lab13/TestProcessBuilder.java
{link}
3
Współdzielenie zasobów
Uwaga!!! Aplikacja może działać w nieskończoność. Czy aplikacja kiedykolwiek się zakończy? Czy jest moż-
liwe, aby
value.i
kiedykolwiek przyjęło wartości -1 lub 2 (działanie programu może być zależne od parametrów
podanych na początku instrukcji)?
1
2
3
4
5
6
package
pl.kielce.tu.lab13;
import
java.util.concurrent.TimeUnit;
public class
TestNoSynchronization
extends
Thread {
final private static int
SIZE = 2;
5
Zgłoś jeśli naruszono regulamin