当前位置:网站首页>Multithreading Basics (III)
Multithreading Basics (III)
2022-06-27 14:03:00 【BobbyCao】
Multithreading Foundation ( 3、 ... and )
One 、 Thread communication
Communication between threads , In fact, multiple threads are operating on the same resource , But the action of the operation is different .
1、 Shared memory communication (while Polling method )
public class ListAdd1 {
private static volatile List<String> list = new ArrayList<>();
public static void main(String[] args) {
Thread t1 = new Thread(()->{
for (int i = 0; i <10; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
list.add("element");
System.out.println(Thread.currentThread().getName() + " towards list Added in " + (i + 1) + " Elements ");
}
},"t1");
Thread t2 = new Thread(()->{
System.out.println(" Get into t2 Threads ...");
while(true) {
if (list.size() ==5) {
System.out.println("t2 Thread receives notification , Thread end ...");
throw new RuntimeException();
}
}
},"t2");
t2.start();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
t1.start();
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
This way, t1 Threads constantly change conditions , Threads t2 Keep passing while Statement detection list1.size() == 5 Is it true , So as to realize the communication between threads . But this way will waste CPU Resources for .
2、wait/notify Mechanism
Use wait/notify Method to realize the communication between threads .( Note that both methods are object Class method , let me put it another way java These two methods are provided for all objects )
① wait and notify Must cooperate synchronized Keyword use
② wait Method release lock ,notify Method does not release the lock
③ wait and notify To be called by the same object
public class ListAdd1 {
private static volatile List<String> list = new ArrayList<>();
public static void main(String[] args) {
// Instantiate a lock, When using wait and notify When , Be sure to cooperate synchronized Keywords to use
final Object lock = new Object();
Thread t1 = new Thread(()->{
synchronized (lock){
for (int i = 0; i <10; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
list.add("element");
System.out.println(Thread.currentThread().getName() + " towards list Added in " + (i + 1) + " Elements ");
if (i == 4) {
System.out.println("t1 towards t2 A notice ");
lock.notify();
}
}
}
},"t1");
Thread t2 = new Thread(()->{
synchronized (lock) {
System.out.println(" Get into t2 Threads ...");
if (list.size() != 5) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("t2 Thread receives notification , Thread end ...");
throw new RuntimeException();
}
},"t2");
t2.start();
t1.start();
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
- 43.
- 44.
- 45.
This method has poor real-time performance , have access to CountDownLatch Improvement .
public class ListAdd1 {
private static volatile List<String> list = new ArrayList<>();
public static void main(String[] args) {
final CountDownLatch countDownLatch = new CountDownLatch(1);
Thread t1 = new Thread(()->{
for (int i = 0; i <10; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
list.add("element");
System.out.println(Thread.currentThread().getName() + " towards list Added in " + (i + 1) + " Elements ");
if (i == 4) {
System.out.println("t1 towards t2 A notice ");
countDownLatch.countDown();
}
}
},"t1");
Thread t2 = new Thread(()->{
System.out.println(" Get into t2 Threads ...");
if (list.size() != 5) {
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("t2 Thread receives notification , Thread end ...");
throw new RuntimeException();
},"t2");
t2.start();
t1.start();
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
Two 、 Use wait/notify Model LinkedBlockQueue
import java.util.LinkedList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class MyQueue {
// 1 You need a collection of loading elements
private LinkedList<Object> list = new LinkedList<Object>();
// 2 You need a counter
private AtomicInteger count = new AtomicInteger(0);
// 3 There needs to be upper and lower limits
private final int minSize = 0;
private final int maxSize;
// 4 Construction method
public MyQueue(int size) {
this.maxSize = size;
}
// 5 Initialize an object For locking
private final Object lock = new Object();
// put(anObject):
// hold anObject Add to BlockingQueue in , If BlockQueue There's no space , The thread calling this method is blocked , until BlockingQueue There's room to move on .
public void put(Object obj) {
synchronized (lock) {
while (count.get() == this.maxSize) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 1 Add elements
list.add(obj);
// 2 Counter accumulation
count.incrementAndGet();
// 3 Notify another thread ( Wake up the )
lock.notify();
System.out.println(" The newly added element is :" + obj);
}
}
// take:
// Take away BlockingQueue Top of the list , if BlockingQueue It's empty , Block to wait until BlockingQueue New data is added .
public Object take() {
Object ret = null;
synchronized (lock) {
while (count.get() == this.minSize) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 1 Do the remove element operation
ret = list.removeFirst();
// 2 Counter decrement
count.decrementAndGet();
// 3 Wake up another thread
lock.notify();
}
return ret;
}
public int getSize() {
return this.count.get();
}
public static void main(String[] args) {
final MyQueue mq = new MyQueue(5);
mq.put("a");
mq.put("b");
mq.put("c");
mq.put("d");
mq.put("e");
System.out.println(" The length of the current container :" + mq.getSize());
Thread t1 = new Thread(() -> {
mq.put("f");
mq.put("g");
}, "t1");
t1.start();
Thread t2 = new Thread(() -> {
Object o1 = mq.take();
System.out.println(" The removed element is :" + o1);
Object o2 = mq.take();
System.out.println(" The removed element is :" + o2);
}, "t2");
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
t2.start();
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
- 43.
- 44.
- 45.
- 46.
- 47.
- 48.
- 49.
- 50.
- 51.
- 52.
- 53.
- 54.
- 55.
- 56.
- 57.
- 58.
- 59.
- 60.
- 61.
- 62.
- 63.
- 64.
- 65.
- 66.
- 67.
- 68.
- 69.
- 70.
- 71.
- 72.
- 73.
- 74.
- 75.
- 76.
- 77.
- 78.
- 79.
- 80.
- 81.
- 82.
- 83.
- 84.
- 85.
- 86.
- 87.
- 88.
- 89.
- 90.
- 91.
- 92.
- 93.
- 94.
- 95.
- 96.
- 97.
- 98.
- 99.
- 100.
- 101.
- 102.
- 103.
- 104.
- 105.
- 106.
- 107.
3、 ... and 、 The singleton pattern
1、double check instance
public class DubbleSingleton {
private volatile static DubbleSingleton ds;
// 1、 Private constructor
private DubbleSingleton() {
}
// 2、 Public method internal , Double check
public static DubbleSingleton getDs() {
if (ds == null) {
try {
// Simulate the preparation time of the initialization object ...
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (DubbleSingleton.class) {
if (ds == null) {
ds = new DubbleSingleton();
}
}
}
return ds;
}
public static void main(String[] args) {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println(DubbleSingleton.getDs().hashCode());
}
}, "t1");
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println(DubbleSingleton.getDs().hashCode());
}
}, "t2");
Thread t3 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println(DubbleSingleton.getDs().hashCode());
}
}, "t3");
t1.start();
t2.start();
t3.start();
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
- 43.
- 44.
- 45.
- 46.
- 47.
- 48.
- 49.
- 50.
- 51.
- 52.
2、static inner class
public class Singletion {
private Singletion() {
}
private static class InnerSingletion {
private static Singletion single = new Singletion();
}
public static Singletion getInstance() {
return InnerSingletion.single;
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
边栏推荐
- Axi bus
- 以前国产手机高傲定价扬言消费者爱买不买,现在猛降两千求售
- 清华&商汤&上海AI&CUHK提出Siamese Image Modeling,兼具linear probing和密集预测性能!...
- Library management system
- Summary of basic usage of command line editor sed
- 全球芯片市场或陷入停滞,中国芯片逆势扩张加速提升自给率
- Domestic database disorder
- Semaphore of thread synchronization
- [a complete human-computer interface program framework]
- Too many requests at once, and the database is in danger
猜你喜欢

Practice of constructing ten billion relationship knowledge map based on Nebula graph

OpenSSF安全计划:SBOM将驱动软件供应链安全

【微服务|Sentinel】热点规则|授权规则|集群流控|机器列表

Implementing springboard agent through SSH port forwarding configuration
Principle Comparison and analysis of mechanical hard disk and SSD solid state disk

After the deployment is created, the pod problem handling cannot be created

Axi bus

阅读别人的代码,是一种怎样的体验

American chips are hit hard again, and another chip enterprise after Intel will be overtaken by Chinese chips

External memory
随机推荐
Step by step expansion of variable parameters in class templates
Shell concise tutorial
Quickly set up a website to visit foreign countries, set up SS and start BBR to quickly surf the Internet
Getting to know cloud native security for the first time: the best guarantee in the cloud Era
快速搭建一个自己的访问国外网站,搭建ss并开启bbr快速上网
CMOS level circuit analysis
External memory
CCID Consulting released the database Market Research Report on key application fields during the "14th five year plan" (attached with download)
基于 xml 配置文件的入门级 SSM 框架整合
A method to realize automatic renaming of pictures uploaded by WordPress
[business security 03] password retrieval business security and interface parameter account modification examples (based on the metinfov4.0 platform)
【业务安全-01】业务安全概述及测试流程
JVM performance tuning and monitoring tools -- JPS, jstack, jmap, jhat, jstat, hprof
【每日3题(3)】盒子中小球的最大数量
Completely solve the problem of Chinese garbled code in Web Engineering at one time
Too many requests at once, and the database is in danger
[problem solving] which nodes are run in tensorflow?
Prometheus 2.26.0 new features
美国芯片再遭重击,继Intel后又一家芯片企业将被中国芯片超越
基于 Nebula Graph 构建百亿关系知识图谱实践