日期:2014-05-17  浏览次数:20725 次

关于线程同步synchronized的问题
Java code

public class MessageUtils extends Thread{
    private boolean flag = true;
    public void run() {
        while (this.flag) {
            try {
                Thread.sleep(300000L);     //5分钟
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
            while (true) {
                autoValidator();
                try {
                    Thread.sleep(300000L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    //靠线程每5分钟运行提交一次
    public void autoValidator(){
        //…………
        if(condition1){
            sendMessage(id,type);
        }
        else if(condition2){
            sendMessage(id,type);
        }
        //…………
    }
    

    //手动提交
     public static int sendMessage(String companyid, String type){
        int result = 0;
        //…………
        return result;
     }

}


线程每五分钟运行一次autoValidator(),由于有时候sendMessage()向接口提交的数据量比较大,在页面手动运行sendMessage时接口那边的状态值还没返回来如果恰巧线程又在运行,会出现重复提交数据的现象,想用synchronized来解决,怎么解决?

------解决方案--------------------
因为你的sendMessage()是static的,所以最简单的方式就是:

public static synchronized int sendMessage(String companyid, String type){


------解决方案--------------------
synchronized是达不到目的的,后台应该设置一个标志来判断数据是否已经提交过
synchronized只是协调线程工作,线程本身并不知道什么数据被提交过,什么没有被提交,加上synchronize只能让线程等待手动执行的结束后线程才执行,但并没有终止线程继续执行,所以线程还是会重复提交数据