-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEjemplo04Notifications.java
87 lines (72 loc) · 1.81 KB
/
Ejemplo04Notifications.java
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
class Message {
private String msg;
public Message(String msg){
this.msg = msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getMsg() {
return msg;
}
}
class Waiter implements Runnable {
private Message msg;
public Waiter(Message m){
this.msg = m;
}
@Override
public void run() {
String name = Thread.currentThread().getName();
synchronized(msg) {
// Region de exclusion mutua
try {
System.out.println(name + " Se esta esperando");
msg.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(name + " Se esta puede continuar");
}
}
}
class Notifier implements Runnable {
private Message msg;
public Notifier(Message m){
this.msg = m;
}
@Override
public void run() {
String name = Thread.currentThread().getName();
System.out.println(name + " se inicio");
try {
synchronized(msg) {
// Region de exclusion mutua
//////////////////
Thread.sleep(3000);
msg.setMsg(name + "Este es otro mensaje");
//////////////////
//msg.notify();
msg.notifyAll();
System.out.println(name + " Se esta puede continuar");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class Ejemplo04Notifications {
public static void main(String[] args) {
Message msg = new Message("Cadena de inicio");
Waiter waiter = new Waiter(msg);
Thread t1 = new Thread(waiter,"waiter");
t1.start();
Waiter waiter1 = new Waiter(msg);
Thread t2 = new Thread(waiter1,"waiter1");
t2.start();
Notifier notifier = new Notifier(msg);
Thread t3 = new Thread(notifier,"notifier");
t3.start();
System.out.println("Los 3 hilos se han inicio");
}
}