当前位置:网站首页>Concurrent programming day01
Concurrent programming day01
2022-07-25 02:53:00 【Novice Xiaobai Xiaoyi】
Concurrent programming
1、 Three elements of concurrent programming
- Atomicity : Or it's all done , All or nothing
- Orderability : The program thread proceeds orderly ( Through lock )
- visibility : The process of modification can be seen
The nature of concurrent programming : make the best of CPU Resources for
The difference between a process and a thread
Process is the basic unit of resource allocation , for example qq These are the processes
Thread is the basic unit of task scheduling , A process contains multiple threads
java There are two threads by default main gc
1.1 Multithreading review
Thread and Runnable( Commonly used )
//MyTread package com.thread; public class MyThread01 extends Thread{ @Override public void run() { System.out.println("i start"); } } ///test public class ThreadDemo01 { public static void main(String[] args) { Thread t1 = new MyThread01(); t1.start(); } } //runnable public class Runable1 implements Runnable{ @Override public void run() { System.out.println(" I started a "); } } //test public class RunTest { public static void main(String[] args) { new Thread(new Runable1()).start(); } }
1.2 Daemons and non daemons
- The guardian thread : stay start Before using setDaemon Method to set the thread as a guard thread , The daemon thread cannot execute until other non daemon threads have finished executing
- Non-daemon thread : The threads we usually use are non daemon threads by default
1.3 When we start a thread, why is it start Start instead of calling directly run Method
reason : Call directly run The way is to put run As a normal method call ,run Method is an ordinary method , Not really starting a thread So to start the thread, you need to really remove the use start Method
1.4 join Method
practical join After that, this thread will finish executing preferentially
1.5 State of thread
- new Freshmen
- function runnable
- Blocking bloked
- Overtime waiting
- End
1.6 wait/sleep difference
wait yes object --> Must be in sync block , No need to catch exceptions , Can release the lock
sleep yes Thread----> It won't release the lock , Need to catch exception
2、synchronized keyword
2.1 The object of the lock
The loading instance method is added to the object , Adding to a static method is adding .class On the file
2.2 The essence of lock
After sharing resources, multiple thread operations will cause some problems , By locking, we can ensure that only one thread can access resources at a time
2.3 lock lock (**)
Tradition Synchronized The essence : Queuing , Release the lock when the object finishes taking the lock
lock Interface Common implementation class ReentranLock
Fair lock : First come, first served
Not fair lock : You can jump in line ( Default )
lock.lock();// Lock
try{
Business code ;
}catch{
}
finally{
lock.unlock();// Unlock
}
Synchronized And lock The difference between
- Synchronized yes java keyword ,lock It's a java class
- Synchronized Unable to determine lock status ,lock You can judge the state of the lock
- Synchronized Will automatically release the lock ,lock You must release the lock manually. If you do not release the lock, a deadlock will occur
- Syn Threads 1 Blocking thread 2 will wait ,lock The lock won't wait
- syn Reentrant lock , Do not interrupt unfairness ,lock, Relocatable lock
- syn Suitable for a small amount of code ,lock Suitable for a large number of code
3 wait And notify
3.1 Producer consumer
If there is no product, inform the producer to produce
formula : Judge wait , Business , notice
public class Customer implements Runnable{
private Box b;
public Customer(Box b) {
this.b = b;
}
@Override
public void run() {
while (true) {
b.get();
}
}
}
public class producer implements Runnable {
private Box b;
public producer(Box b) {
this.b = b;
}
@Override
public void run() {
for (int i = 5; i > 0; i--) {
b.put(i);
}
}
}
//box
public class Box {
private int milk;
private boolean state = false;
public synchronized void put(int milk){
if (state){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.milk=milk;
System.out.println(" Sent to me "+milk+" milk ");
state = true;
notifyAll();
}
public synchronized void get(){
if (!state){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(" The user got "+this.milk+" milk ");
state=false;
notifyAll();
}
}
//test
public class ThreadDemo {
public static void main(String[] args) {
Box b = new Box();
producer p =new producer(b);
Customer c = new Customer(b);
Thread t1 = new Thread(p);
Thread t2 = new Thread(c);
t1.start();
t2.start();
}
}
public class PcTestDemo {
public static void main(String[] args) {
Pcdemo pc = new Pcdemo();
new Thread(()->{
try {
for (int i = 0; i < 10; i++) {
pc.add();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
},"A").start();
new Thread(()->{
try {
for (int i = 0; i < 10; i++) {
pc.denumber();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
},"B").start();
}
}
class Pcdemo{
private int number=0;
public synchronized void add() throws InterruptedException {
// Determine whether you need to wait
while (number!=0){
this.wait();
}
number++;
System.out.println(Thread.currentThread().getName()+" The first "+number);
// Wake up other threads
this.notifyAll();
}
public synchronized void denumber() throws InterruptedException {
while (number!=1){
this.wait();
}
number--;
System.out.println(Thread.currentThread().getName()+number);
this.notifyAll();
}
}
*** Pay attention to if Judgment will produce false awakening
So the judgment is to adopt while Loop to judge
边栏推荐
- Study notes of filebeat
- Read and upgrade st-link chip information and SWD burning media through STM32 stlink utility tool
- The file in scanpy1.9.1 cannot be read in scanpy1.7.2. The problem is solved
- Physical experiment simulation
- Permanently mount the image steps
- My creation anniversary (3rd Anniversary)
- Interview question -- event cycle
- Learning record Xi
- [jailhouse article] certify the uncertified rewards assessment of virtualization for mixed criticality
- Go common standard library -time
猜你喜欢

JS foundation -- regular expression

TS uses a third-party library, and there is no type declaration file error handling

YouTube Download and (batch) Download

JS written test questions -- random numbers, array de duplication

What should I do when the interface encounters jsonstring

JS foundation -- task queue and event loop

Beginners must see the markdown User Guide

B2B e-commerce trading platform of heavy metal industry: breaking the state of data isolation and improving the benefits of heavy metal industry

JS written test question -- realize the flat function of array

MySQL common function summary, very practical, often encountered in interviews
随机推荐
R language one page and many pictures
Wechat sports field reservation of the finished works of the applet graduation project (5) assignment
Domain driven model (DDD)
SQL Server 2022 installation
Flutter apple native Pinyin keyboard input exception on textfield | Pinyin input process callback problem
Go common standard library -time
Resolve the error: org.apache.ibatis.binding.bindingexception
JS foundation -- task queue and event loop
Text reading end judgment
JS foundation -- JSON
Is it necessary to increase the number of milliseconds and save several KB of memory in the program?
2022-07-19: all factors of F (I): I are added up after each factor is squared. For example, f (10) = 1 square + 2 square + 5 square + 10 square = 1 + 4 + 25 + 100 = 130.
Can PostgreSQL CDC only connect to the main database? Connection from the library reports an error logical decoden
JS foundation -- regular expression
# CF #808 Div.2(A - C)
Learning record 12
Insertion of balanced binary tree (AVL tree)
Use pytest + allure to show the chart results (3)
Map set learning
Digital commerce cloud fine chemical industry management platform integrated informatization solution