package com.fish.thread;
publicclass Test22 {
publicstaticvoid main(String[] args) {
Inc inc=new Inc(0);
Dec dec=new Dec(1);
for( int i=0;i<2;i++){
new Thread(inc).start();
new Thread(dec).start();
}
}
}
class Inc implements Runnable{
int j=10;
Object mutex;
public Inc(Object mutex) {
this.mutex = mutex;
}
@Override
publicvoid run() {
// TODO Auto-generated method stub
synchronized (mutex) {
for(int i=10;i>0;i--){
System.out.println(Thread.currentThread().getName()+"*******j="+j--);
}
}
}
}
class Dec implements Runnable{
int j=10;
Object mutex;
public Dec(Object mutex) {
this.mutex = mutex;
}
@Override
publicvoid run() {
// TODO Auto-generated method stub
synchronized (mutex) {
for(int i=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
这个说明t0,t2是同步的,资源也是gx。这两个为一组,另外两个为另一组,两组之间是异步的。
同步的标志就是1一个执行,另一个必须等待。
用runnable的好处是可以实现资源资源共享。不是说thread不能是实现资源共享。只是runnable更好。