NutzCN Logo
问答 Runnable 传参异常
发布于 53天前 作者 Hamming 155 次浏览 复制 上一个帖子 下一个帖子
标签:

Runnable 传参异常 定义如下 线程

public class RankingSync implements Runnable {


    private Dao dao;

    private String url;

    public RankingSync(Dao dao, String url) {
        this.dao =dao;
        this.url = url;
    }
}

定义线程池

public synchronized void syncData() {
		int maxpage = 132;

		ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
				.setNameFormat("ranking-data-%d").build();

		//Common Thread Pool
		ExecutorService pool = new ThreadPoolExecutor(8, 16,
				0L, TimeUnit.MILLISECONDS,
				new LinkedBlockingQueue<Runnable>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());

		for(int i=0;i<=maxpage;i++){
			StringBuffer url =new StringBuffer();
			if(0==i){
				url.append("https://xxx.com");
			}else {
				url.append("https://xxx.com"+ i +"-1-.htm?rank=&uprank=");
			}
			//ioc才能实现依赖注入
			RankingSync rankingSync = new RankingSync(this.dao(),url.toString());
			pool.execute(()->rankingSync.run());
		}
		pool.shutdown();

	}

执行的url 出现重复 这个是为什么呢

2 回复

如何看出重复了呢?

每个线程 运行的url 都是

https://xxx.com131-1-.htm?rank=&uprank=

我创建了一个 线程类 获取统计数 就解决了

package io.nutz.nutzsite.common.bean;

import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockCount {

    private final ReentrantLock lock = new ReentrantLock();

    private int count = 0;

    public int getCount() {
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + " gets Count: " + count);
            return count++;
        } finally {
            lock.unlock();
        }
    }
    public synchronized int getCountValue() {
        return count;
    }
}

添加回复
请先登陆
回到顶部