Synchronized (同步) block使用实例

来源:互联网 发布:tscttp244pro标签软件 编辑:程序博客网 时间:2024/06/03 21:27


package com.synchronoizre;

class Counter {
    private int c = 0;
    public void increase(){
        c++;
    }
    public void decrease(){
        c--;
    }
    public int value(){
        return c;
    }
}
    public class SynchronizeDemo {
        public static void main(String[] args) {
            final Counter counter = new Counter();
            Thread t1  = new Thread(new Runnable(){

                @Override
                public void run() {
                    synchronized(counter){
                    System.out.println("现在的c值:"+counter.value());
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException ex) {
                      
                    }
                    counter.increase();
                    System.out.println("加一后c的值:"+counter.value());
                    }
                }
               
            });
                  
           
            Thread t2  = new Thread(new Runnable(){

                @Override
                public void run() {
                    //加一个同步块
                    synchronized(counter){
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException ex) {
                      
                    }
                    counter.decrease();
                    }
                }
               
            });
                   
            t1.start();
            t2.start();
           
        }
   
}

0 0
原创粉丝点击