开发者社区> 问答> 正文

Mongodb在java中,多线程update时报错。

 public class LocationPressureTest {
    private Todo todo;
    private int number;

    static Mongo mg = new Mongo("localhost", 27017);
    static DB db = mg.getDB("location_pressure_test_db");
    static DBCollection col = db.getCollection("location_pressure_test_col");


    public interface Todo {
        public void doIt();
    }
    public LocationPressureTest(int number, Todo todo) {
        this.number = number;
        this.todo = todo;
    }

    public void start() {
        for(int i = 0; i < number; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    while(true) {
                        if(todo != null) {
                            try {
                                todo.doIt();
                            } catch (Throwable t) {
                                t.printStackTrace();
                                break;
                            }
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }).start();
        }
    }
    /**
     * @param args
     */
    public static void main(String[] args) {
        LocationPressureTest loadRunner = null;
        loadRunner = new LocationPressureTest(347, new Todo() {
            @Override
            public void doIt() {
                System.out.println(Thread.currentThread());
                col.update(col.findOne(new BasicDBObject("_id", String.valueOf(Math
                        .round(Math.random() * 5000000)))),
                        new BasicDBObject("$set", new BasicDBObject("coordinates",
                                new Double[] { Math.random() * 360 - 180,
                                        Math.random() * 360 - 180 })));
            }
        });
        loadRunner.start();

        synchronized (loadRunner) {
            try {
                loadRunner.wait();
            } catch (Exception e) {
            }
        }
    }

}

报错如下
1

展开
收起
落地花开啦 2016-02-27 16:45:44 2751 0
1 条回答
写回答
取消 提交回答
  • 喜欢技术,喜欢努力的人

    不用设置mongodb的线程数,只需要把number变量的值设小一点就行了,比如10.

    2019-07-17 18:49:04
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载