PackageCom. Fish. thread;
PublicclassTest22 {
PublicstaticvoidMain (string [] ARGs ){
INC Inc =NewINC (0 );
Dec =NewDec (1 );
For(
IntI = 0; I <2; I ++ ){
NewThread (INC). Start ();
NewThread (DEC). Start ();
}
}
}
ClassINC
ImplementsRunnable {
IntJ = 10;
Object mutex;
PublicINC (Object mutex ){
This. Mutex = mutex;
}
@ Override
PublicvoidRun (){
//
TodoAuto-generated method stub
Synchronized(Mutex ){
For(IntI = 10; I> 0; I --){
System. Out. println (thread. currentthread (). getname () + "******** J =" + j --);
}
}
}
}
ClassDec
ImplementsRunnable {
IntJ = 10;
Object mutex;
PublicDec (Object mutex ){
This. Mutex = mutex;
}
@ Override
PublicvoidRun (){
//
TodoAuto-generated method stub
Synchronized(Mutex ){
For(IntI = 10; I> 0; I --){
System. Out. println (thread. currentthread (). getname () + "& J =" + J ++ );
}
}
}
}
Thread-0 ******** J = 10
Thread-0 ******** J = 9
Thread-0 ******** J = 8
Thread-1 & J = 10
Thread-0 ******** J = 7
Thread-1 & J = 11
Thread-0 ******** J = 6
Thread-0 ******** J = 5
Thread-0 ******** J = 4
Thread-1 & J = 12
Thread-0 ******** J = 3
Thread-1 & J = 13
Thread-0 ******** J = 2
Thread-1 & J = 14
Thread-0 ******** j = 1
Thread-1 & J = 15
Thread-1 & J = 16
Thread-2 ******** J = 0
Thread-1 & J = 17
Thread-2 ******** J =-1
Thread-2 ******** J =-2
Thread-2 ******** J =-3
Thread-2 ******** J =-4
Thread-2 ******** J =-5
Thread-2 ******** J =-6
Thread-2 ******** J =-7
Thread-2 ******** J =-8
Thread-2 ******** J =-9
Thread-1 & J = 18
Thread-1 & J = 19
Thread-3 & J = 20
Thread-3 & J = 21
Thread-3 & J = 22
Thread-3 & J = 23
Thread-3 & J = 24
Thread-3 & J = 25
Thread-3 & J = 26
Thread-3 & J = 27
Thread-3 & J = 28
Thread-3 & J = 29
This indicates that T0, T2 is synchronized, and the resource is GX. The two are one group, the other two are the other, and the two are asynchronous.
The mark of synchronization is one execution, and the other must wait.
Runnable enables resource sharing. It does not mean that thread cannot be used to share resources. Only runnable is better.