Skip to content

Instantly share code, notes, and snippets.

@onlythinking
Created June 23, 2020 07:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save onlythinking/ba7ca7aa5faf00a58f4cedae474fa6f6 to your computer and use it in GitHub Desktop.
Save onlythinking/ba7ca7aa5faf00a58f4cedae474fa6f6 to your computer and use it in GitHub Desktop.
多线程写入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