多线程
多线程
一羊化氮
这个作者很懒,什么都没留下…
展开
-
初识Atomic
场景:i++是线程安全的吗? 首先看段代码: public class Test { static Integer num = 0; public static void main(String[] args) { for (int i = 0; i < 100; i++) { Thread thread = new Thread(() -> { for (int j = 0; j < 100; j+原创 2020-12-14 17:12:50 · 296 阅读 · 0 评论 -
ThreadLocal源码分析
场景 假设在多个线程共用同一个类里面的属性,这里的共用指的是读和写操作,如下代码所示。 public class ThreadLocalTest { private String string; public String getString() { return string; } public void setString(String string) { this.string = string; } public原创 2020-12-10 18:30:14 · 141 阅读 · 0 评论 -
两个线程交替打印0-100的奇偶数
题目:两个线程,其中一个线程打印奇数,另一个打印偶数,交替输出0-100 方法1:自旋判断 开启两个线程,每个线程自旋判断当前值是奇数/偶数,然后打印 public class Test { volatile static int i = 0; public static void main(String[] args) { Thread thread1 = new Thread(() -> { while (i <= 100) {原创 2020-12-08 17:44:13 · 681 阅读 · 2 评论