File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed
Chapter_30/exercise_30_11 Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change 1+ package exercise_30_11 ;
2+
3+ public class Exercise_30_11 {
4+
5+ public static void main (String [] args ) {
6+ Object object1 = new Object ();
7+ Object object2 = new Object ();
8+ Thread thread1 = new Thread (new Task (object1 , object2 , 1 ));
9+ Thread thread2 = new Thread (new Task (object2 , object1 , 2 ));
10+ thread1 .start ();
11+ thread2 .start ();
12+ }
13+
14+ public static class Task implements Runnable {
15+ public Object object1 ;
16+ public Object object2 ;
17+ public int taskIndex ;
18+
19+ public Task (Object object1 , Object object2 , int taskIndex ) {
20+ this .object1 = object1 ;
21+ this .object2 = object2 ;
22+ this .taskIndex = taskIndex ;
23+ }
24+
25+ @ Override
26+ public void run () {
27+ System .out .println ("Task" + taskIndex + " is running." );
28+ while (true ) {
29+ synchronized (object1 ) {
30+ System .out .println ("Task" + taskIndex + " locked object1." );
31+ synchronized (object2 ) {
32+ System .out .println ("Task" + taskIndex + " locked object2." );
33+ }
34+ }
35+ }
36+ }
37+ }
38+ }
You can’t perform that action at this time.
0 commit comments