多个线程访问同一个类里面的静态成员变量

如下所示,product1, product2,product3是三个不同的线程,但由于Producer类里面的成员变量count是静态变量,

所以实际上count是三个线程的共享成员变量,对其进行操作时,最好加上锁访问机制。

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;

public class BlockingQueueTest {

	public static void main(String[] args) throws InterruptedException {
		// 声明一个容量为10的缓存队列
		BlockingQueue queue = new LinkedBlockingQueue(10);

		Producer producer1 = new Producer(queue, 1);
		Producer producer2 = new Producer(queue, 2);
		Producer producer3 = new Producer(queue, 3);
		Consumer consumer = new Consumer(queue);

		// 借助Executors
		ExecutorService service = Executors.newCachedThreadPool();
		// 启动线程
		service.execute(producer1);
		service.execute(producer2);
		service.execute(producer3);
		// service.execute(consumer);

		// 执行10s
		Thread.sleep(10 * 1000);
		producer1.stop();
		producer2.stop();
		producer3.stop();

		Thread.sleep(2000);
		// 退出Executor
		// service.shutdown();
	}
}


 
  
package java_thread_delayQueue.blockingqueue;

import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class Producer implements Runnable {

	public Producer(BlockingQueue queue, int x) {
		this.queue = queue;
		this.x = x;
	}

	public void run() {
		String data = null;
		Random r = new Random();

		System.out.println("启动生产者线程!");
		try {
			while (isRunning) {
				System.out.println("正在生产数据...");
				Thread.sleep(r.nextInt(DEFAULT_RANGE_FOR_SLEEP));

				data = "线程"+ x +"data:" + count.incrementAndGet();
				System.out.println("将数据:" + data + "放入队列...");
				System.out.println(data);
				if (!queue.offer(data, 2, TimeUnit.SECONDS)) {
					System.out.println("放入数据失败:" + data);
				}
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
			Thread.currentThread().interrupt();
		} finally {
			System.out.println("退出生产者线程!");
		}
	}

	public void stop() {
		isRunning = false;
	}

	private volatile boolean isRunning = true;
	private BlockingQueue queue;
	private static AtomicInteger count = new AtomicInteger();
	private static final int DEFAULT_RANGE_FOR_SLEEP = 1000;
	
	private int x;

}

你可能感兴趣的:(java)