source: trunk/Shared2.java@ 15

Last change on this file since 15 was 2, checked in by Mattia Monga, 13 years ago

Importazione sorgenti

File size: 1.3 KB
Line 
1class ClasseAttiva extends Thread{
2 protected static int shared = 0;
3 protected static Object lock = new Object();
4 public void run() {
5 while (true) {
6 synchronized(lock){
7 if (shared >= 10) break;
8 try {
9 Thread.sleep(1000);
10 }
11 catch(InterruptedException e){
12 System.err.println(e);
13 }
14 if (shared >= 10){
15 throw new Error("Corsa critica!!!");
16 }
17 System.out.print(this.getName());
18 System.out.print(" s = ");
19 System.out.println(this.shared);
20 shared += 1;
21 }
22 Thread.yield(); // non necessaria, ma favorisce lo scheduling di entrambi
23 }
24 }
25}
26
27
28
29public class Shared2 {
30 public static final void main(final String[] args) {
31 ClasseAttiva o1 = new ClasseAttiva();
32 ClasseAttiva o2 = new ClasseAttiva();
33 o1.start();
34 o2.start();
35 while (true){
36 try {
37 Thread.sleep(1000);
38 }
39 catch(InterruptedException e){
40 System.err.println(e);
41 }
42
43 System.out.println("Main thread");
44 }
45
46 }
47}
48
49
50
Note: See TracBrowser for help on using the repository browser.