实现一个线程安全的计数器

谁说胖子不能爱 提交于 2019-12-24 18:38:33
package com.test;


public class MySafeThread implements Runnable{

    public static volatile int a;

    @Override
    public void run(){
        while (true){
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            MySafeThread.calc();
        }
    }
    //计数 注意加锁sychronized
    private synchronized static void calc(){

        if (a<1000){
            a=++a;
            //现场名称与自增后的值
            System.out.println(Thread.currentThread().getName()+":"+a);
        }
    }
    //开启五个线程进行计数
    public static void main(String[] args) {
        for (int i=0;i<5;i++){
            MySafeThread mySafeThread = new MySafeThread();
            Thread t = new Thread(mySafeThread);
            t.start();
        }
    }
}

第二种方法:

package com.test;


import java.util.concurrent.locks.ReentrantLock;

public class MySafeThread implements Runnable{

    public static volatile int a;
    static ReentrantLock lock = new ReentrantLock();

    @Override
    public void run(){
        while (true){
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            MySafeThread.calc();
        }
    }
    //计数 注意加锁sychronized
    private  static void calc(){
        lock.lock();
        try{
            if (a<1000){
                a=++a;
                //现场名称与自增后的值
                System.out.println(Thread.currentThread().getName()+":"+a);
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }


    }
    //开启五个线程进行计数
    public static void main(String[] args) {
        for (int i=0;i<5;i++){
            MySafeThread mySafeThread = new MySafeThread();
            Thread t = new Thread(mySafeThread);
            t.start();
        }
    }
}

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!