并发
CodeBoyWLC
技术+原理爱好者
展开
-
【并发】终止线程的方式
①执行完run(),线程正常结束②用退出标志终止线程volatile退出标志方法package com.test;import lombok.extern.slf4j.Slf4j;import java.util.Random;import java.util.Timer;import java.util.TimerTask;import java.util.concurrent.*;@Slf4j(topic = "c.TestThreadLocal")public class .原创 2021-05-29 14:06:53 · 85 阅读 · 0 评论 -
【并发】可见性及解决
public class Test32 { static boolean run = true; //加volatile static boolean run = true;即可解决 public static void main(String[] args) throws InterruptedException { Thread t = new Thread(()->{ while(true){ i原创 2021-05-27 18:43:51 · 66 阅读 · 0 评论 -
【并发】活锁
public class TestLiveLock { static volatile int count = 10; static final Object lock = new Object(); public static void main(String[] args) { new Thread(() -> { while (count > 0) { try { Thread.sl原创 2021-05-22 16:39:19 · 55 阅读 · 0 评论 -
【并发】哲学家就餐问题:用reentrantLock解决
public class TestDeadLock { public static void main(String[] args) { Chopstick c1 = new Chopstick("1"); Chopstick c2 = new Chopstick("2"); Chopstick c3 = new Chopstick("3"); Chopstick c4 = new Chopstick("4"); Cho原创 2021-05-22 16:38:20 · 160 阅读 · 0 评论 -
【并发】哲学家就餐问题
package com.test;import lombok.extern.slf4j.Slf4j;import java.util.Random;public class TestDeadLock { public static void main(String[] args) { Chopstick c1 = new Chopstick("1"); Chopstick c2 = new Chopstick("2"); Chopstick原创 2021-05-22 16:36:14 · 59 阅读 · 0 评论 -
【并发】线程死锁
package com.test;import lombok.extern.slf4j.Slf4j;@Slf4j(topic = "c.TestDeadLock")public class TestDeadLock { public static void main(String[] args) { test1(); } private static void test1() { Object A = new Object();原创 2021-05-22 16:34:48 · 79 阅读 · 0 评论 -
【并发】交替输出
public class Test { public static void main(String[] args) throws InterruptedException { AwaitSignal awaitSignal = new AwaitSignal(5); Condition a = awaitSignal.newCondition(); Condition b = awaitSignal.newCondition(); C原创 2021-05-22 16:32:31 · 77 阅读 · 0 评论 -
【并发】同步模式:顺序控制
public class Test25 { static final Object lock = new Object(); // 表示 t2 是否运行过 static boolean t2runned = false; public static void main(String[] args) { Thread t1 = new Thread(() -> { synchronized (lock) {原创 2021-05-22 16:31:30 · 60 阅读 · 0 评论 -
【并发】管程:同步模式-保护性暂停
class GuardedObject { private Object response; private final Object lock = new Object(); public Object get() {synchronized (lock) {// 条件不满足则等待while (response == null) {try {lock.wait();} catch (InterruptedException e) {e.printStackTrace();} }re原创 2021-05-22 16:30:35 · 34 阅读 · 0 评论 -
【并发】管程:wait/notify的简单使用
public class TestWaitNotify { final static Object obj = new Object(); public static void main(String[] args) { new Thread(() -> { synchronized (obj) { log.debug("执行...."); try {原创 2021-05-22 16:28:59 · 89 阅读 · 0 评论 -
【并发】管程:共享资源问题及解决
public class Test { static int counter = 0; public static void main(String[] args) throws InterruptedException { Thread t1 = new Thread(() -> { for (int i = 0; i < 5000; i++) { counter++; } }, "t1"); Thread t2 = new Thread(() ->原创 2021-05-22 16:25:40 · 75 阅读 · 0 评论