多线程4synchronized保证线程安全的原理
作者:
RyanHugo | 来源:发表于
2020-03-13 21:02 被阅读0次
代码
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();
}
}
本文标题:多线程4synchronized保证线程安全的原理
本文链接:https://www.haomeiwen.com/subject/yhvyshtx.html
网友评论