Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
多线程写入volatile变量
package com.quantum1tech.pdl.app;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* <p> The describe </p>
*
* @author Li Xingping
*/
@Slf4j
public class VolatileThreadTest {
public static void main(String[] args) throws InterruptedException {
int size = 10;
CountDownLatch countDownLatch = new CountDownLatch(size);
ExecutorService executor = Executors.newFixedThreadPool(size + 1);
ShareObject share = new ShareObject();
executor.execute(new ReadTask(share));
for (int i = 0; i < size; i++) {
executor.execute(new WriterTask(share, countDownLatch));
}
countDownLatch.await();
}
public static class ReadTask implements Runnable {
private final ShareObject share;
public ReadTask(ShareObject share) {
this.share = share;
}
@Override
public void run() {
for (; ; ) {
log.info("当前数据{}", share.getCounter());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// ignore
}
}
}
}
public static class WriterTask implements Runnable {
private final ShareObject share;
private final CountDownLatch countDownLatch;
public WriterTask(ShareObject share, CountDownLatch countDownLatch) {
this.share = share;
this.countDownLatch = countDownLatch;
}
@Override
public void run() {
countDownLatch.countDown();
share.increase();
}
}
@Data
public static class ShareObject {
private volatile int counter;
public int getCounter() {
return counter;
}
public void increase() {
try {
Thread.sleep(400);
} catch (InterruptedException e) {
// ignore
}
this.counter++;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment