java多线程 计数,Java多线程-线程安全计数器

I'm starting off with a very simple example in multithreading. I'm trying to make a threadsafe counter. I want to create two threads that increment the counter intermittently to reach 1000. Code below:

public class ThreadsExample implements Runnable {

static int counter = 1; // a global counter

public ThreadsExample() {

}

static synchronized void incrementCounter() {

System.out.println(Thread.currentThread().getName() + ": " + counter);

counter++;

}

@Override

public void run() {

while(counter<1000){

incrementCounter();

}

}

public static void main(String[] args) {

ThreadsExample te = new ThreadsExample();

Thread thread1 = new Thread(te);

Thread thread2 = new Thread(te);

thread1.start();

thread2.start();

}

}

From what I can tell, the while loop right now means that only the first thread has access to the counter until it reaches 1000. Output:

Thread-0: 1

.

.

.

Thread-0: 999

Thread-1: 1000

How do I fix that? How can I get the threads to share the counter?

解决方案

Both threads have access to your variable.

The phenomenon you are seeing is called thread starvation. Upon entering the guarded portion of your code (sorry I missed this earlier), other threads will need to block until the thread holding the monitor is done (i.e. when the monitor is released). Whilst one may expect the current thread pass the monitor to the next thread waiting in line, for synchronized blocks, java does not guarantee any fairness or ordering policy to which thread next recieves the monitor. It is entirely possible (and even likely) for a thread that releases and attempts to reacquire the monitor to get hold of it over another thread that has been waiting for a while.

From Oracle:

Starvation describes a situation where a thread is unable to gain regular access to shared resources and is unable to make progress. This happens when shared resources are made unavailable for long periods by "greedy" threads. For example, suppose an object provides a synchronized method that often takes a long time to return. If one thread invokes this method frequently, other threads that also need frequent synchronized access to the same object will often be blocked.

Whilst both of your threads are examples of "greedy" threads (since they repeatedly release and reacquire the monitor), thread-0 is technically started first, thus starving thread-1.

The solution is to use a concurrent synchronization method that supports fairness (e.g. ReentrantLock) as shown below:

public class ThreadsExample implements Runnable {

static int counter = 1; // a global counter

static ReentrantLock counterLock = new ReentrantLock(true); // enable fairness policy

static void incrementCounter(){

counterLock.lock();

// Always good practice to enclose locks in a try-finally block

try{

System.out.println(Thread.currentThread().getName() + ": " + counter);

counter++;

}finally{

counterLock.unlock();

}

}

@Override

public void run() {

while(counter<1000){

incrementCounter();

}

}

public static void main(String[] args) {

ThreadsExample te = new ThreadsExample();

Thread thread1 = new Thread(te);

Thread thread2 = new Thread(te);

thread1.start();

thread2.start();

}

}

note the removal of the synchronized keyword in favor of the ReentrantLock within the method. Such a system, with a fairness policy, allows long waiting threads a chance to execute, removing the starvation.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值