代码
public class Sequence {
private int value;
// synchronized在普通方法,内置锁就是当前实例
public synchronized int getNext(){
return value++;
}
// synchronized修饰静态方法,内置锁是当前的Class字节码对象
public static synchronized int getPrevious() {
return 0;
}
public static void main(String[] args) {
synchronized (Sequence.class) {
}
Sequence s = new Sequence();
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println(Thread.currentThread().getName()+" "+s.getNext());
while(true){
System.out.println(Thread.currentThread().getName()+" "+s.getNext());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
System.out.println(Thread.currentThread().getName()+" "+s.getNext());
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start();
}
}
网友评论