进行2个线程计数器-从开始到结束值计数。应当为每个计数显示计数器的值。一个线程被设置为计数值小于另一个线程。当一个线程计数到设定点时,另一个线程停止并完成其执行。这是我的任务,因此我使用AtomicBoolean run = new AtomicBoolean(true);提出了解决方案。
/**
* Implements {@link Runnable} and his method {@link Runnable#run} to run until stop is set to true
* and count is less than maxCount.
*/
public class Counter implements Runnable {
private static final Logger logger = LoggerFactory.getLogger(Counter.class);
private static final String MAX_COUNT_EXCEPTION_MESSAGE = "maxCount should be bigger than zero!";
private static final int NUMBER_TO_CHECK_MAX_COUNT_VALIDATION = 1;
private AtomicBoolean run;
private int count;
private int maxCount;
/**
* Constructs a counter with zero count and run equal to true with a specified maxCount.
*
* @param maxCount of the counter
* @throws IllegalArgumentException if maxCount is smaller than 1
*/
Counter(int maxCount, AtomicBoolean run) {
if (maxCount < NUMBER_TO_CHECK_MAX_COUNT_VALIDATION) {
throw new IllegalArgumentException(MAX_COUNT_EXCEPTION_MESSAGE);
}
this.maxCount = maxCount;
this.run = run;
}
/**
* Entry point.
* <p>
* Runs until run is set to false and count is less than maxCount.
* <p>
* On every loop {@link Counter} increment count with 1 and print the count.
*/
@Override
public void run() {
while (count < maxCount && run.get()) {
incrementCount();
logger.info(this + " : " + count);
}
run.set(false);
}
/**
* Used for obtaining current value for the count.
*
* @return count.
*/
int getCount() {
return count;
}
/**
* Increment the count.
*/
private void incrementCount() {
count++;
}
}
/**
* Runs two counters and print the counting for both of them until one reach his maxCount then both are stopped.
*/
public class RunnerTwoCounters {
private static final Logger logger = LoggerFactory.getLogger(RunnerTwoCounters.class);
public static void main(String[] args) throws InterruptedException {
AtomicBoolean run = new AtomicBoolean(true);
Counter counter1 = new Counter(2, run);
Thread thread1 = new Thread(counter1);
Counter counter2 = new Counter(10, run);
Thread thread2 = new Thread(counter2);
thread1.start();
thread2.start();
thread1.join();
thread2.join();
logger.info(counter1 + " " + counter1.getCount());
logger.info(counter2 + " " + counter2.getCount());
}
}
我如何使相同的东西工作,但没有Atomicboolean仅仅用于对象锁并对其进行一些同步?
您可以使用等待和通知来控制过程的继续。两个线程都使用其类的实例作为锁。
public void start() {
Thread start = new Thread(() -> {
for (int i = 0; i <= setPoint; i++) {
System.out.println(i);
}
synchronized (this) {
// done so wake up continuation thread
notify();
}
});
Thread finish = new Thread(() -> {
try {
synchronized (this) {
wait();
}
} catch (InterruptedException ie) {
}
for (int i = setPoint + 1; i <= endPoint; i++) {
System.out.println(i);
}
});
start.start();
finish.start();
}
}