多线程4synchronized保证线程安全的原理

2020-03-13  本文已影响0人  RyanHugo

代码

补充https://www.cnblogs.com/skywang12345/p/3479202.html

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();
    
    
    }
    
}
上一篇 下一篇

猜你喜欢

热点阅读