当前位置:网站首页>Day_ 19 multithreading Basics
Day_ 19 multithreading Basics
2022-06-30 02:11:00 【Love Siyi alone】
PrintStream/PrintWriter
PrintStream/PrintWriter : Output stream -> Print byte output stream / Print character output stream
PrintStream : System.out The object type of the system standard output stream
Special output methods : println( Any type of object );
PrintWriter : Very compatible
Auto refresh and auto wrap :
Automatically refresh : Must be creating PrintWriter Object, turn on the auto refresh switch , And the method of outputting data must use println(),printf(),format()
Word wrap : Must be called when exporting println()
// summary : To refresh and wrap lines automatically, you must turn on the refresh switch and call println Method to output data !!
Construction method :
PrintWriter(String fileName) : Pass in the destination file address directly ;// The auto refresh switch cannot be set
PrintWriter(File file) : Pass in File object ;
// Converted flow , Packaging flow
PrintWriter(OutputStream out) : It can receive byte stream objects ;
PrintWriter(Writer out) : You can also receive character stream objects ;
// Construction method with automatic refresh switch
PrintWriter(OutputStream out, boolean autoFlush)
PrintWriter(Writer out, boolean autoFlush)
PrintWriter(String fileName) The source code of the construct :
//this(Writer out, boolean autoFlush)
this(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName))),
false);
PrintWriter(Writer out) The source code of the construct :
///this(Writer out, boolean autoFlush)
this(out, false);
The method of writing :
//PrintWriter There must be five ways to write data in the ordinary character output stream
Special writing method :
void println( Any type of object ) : Output and wrap
void print( Any type of object ) : Output does not wrap
Interesting cases : Create a superflow object
Basic flow : FileOutputStream Encapsulated into a package with : Automatically refresh , Word wrap , Additional writing , Efficient character stream for setting the encoding method for writing
Additional writing : FileOutputStream/FileWriter
Automatically refresh , Word wrap : PrintWriter
Set the encoding method for writing : OutputStreamWriter
Efficient flow : BufferedWriter
PrintWriter pw = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream(" Destination file address ",true/* Additional writing */)," Coding format "/* Set the encoding format */)),true/* Auto refresh switch */);

Properties
Properties: Double column set -> It and IO There are very convenient operation methods between streams
matters needing attention :
1. establish Properties Object time , You cannot give generics ; Because the parent class writes the generics to death (Properties The generics of are <Object,Object>)
2. To achieve and IO A convenient way to interact with streams , Must ask for Properties Data types of keys and values in the collection Must be String type
Construction method :
Properties Collection name = new Properties();
Additions and deletions : and HashMap The same way
Replace put Method : Object setProperty(String key, String value)
Replace get Method : String getProperty(String key)
Replace keySet Method : Set<String> stringPropertyNames()
Properties and IO Methods of interaction :
One click to store the contents of the collection in a file :
void store(OutputStream out,String comment)
void store(Writer out,String comment)
One click to load the attribute set in the file into the set
void load(InputStream in)
void load(Reader in)
Processes and threads
process : Running applications
Threads : Threads exist in the process , A process has at least one thread
Parallel and concurrent
parallel : There are many things happening at the same time
Concurrent : There are many things happening at the same time
Is a multithreaded program parallel or concurrent ?
Multithreaded programs are both parallel and concurrent
CPU How to run multiple programs at the same time ?
1. Collect all threads of these programs , Break up !
2. Let the thread snatch CPU Executive power , When you get it, execute ( Random )
Thread architecture

The first way to start a thread ( Inherit )
1. Create a class , Inherit Thread class
2. Override... In the parent class run Method -> Write the task of thread object by yourself
3. Create subclass objects , And call start() Method to start the thread
The second way to start a thread ( Realization )
Thread Construction method in class :
Thread(Runnable target)
1. Prepare one Runnable Implementation class object of interface ( Implement with class / Anonymous inner class ) , rewrite run Method
2. establish Runnable Implementation class object of
3. establish Thread Class object and put Runnable The implementation class object of the
4. Start thread
Memory map of thread execution

The third way to start a thread ( Threaded tasks with results )
Callable<V> Interface -> Task interface of thread V: After the thread completes the task , The data type of the result
There is only one way : V call()
Intermediate class : FutureTask
FutureTask(Callable<V> callable)
FutureTask(Runnable runnable, V result)
The relationship between class and interface :
1. Runnable Interface yes FutureTask The parent interface
2. FutureTask(Callable<V> callable)
3. Thread(Runnable target)
1. establish Callable<V> Implementation class object of , rewrite call Method to write the task of the thread
2. establish FutureTask object , And pass the task object to FutureTask object
3. establish Thread object , And put FutureTask Object passed to Thread object
4. Thread object calls start Method , Start thread
FutureTask Class V get() Method : ( Blocking method )
Get the result after the thread is executed , You must wait until the thread finishes executing and returns the result !
Thread name setting and getting method
Thread object name setting :
1. Construction method :
Thread(String name)
Thread(Runnable target, String name)
2. Member method :
void setName(String name)
Get the name of the thread object :
Thread Class member methods : String getName()
// If you cannot directly call getName(), You can use it first Thread Static methods in a class :
static Thread currentThread(): Get the current thread object
Thread priority
The default priority of the thread : 5
The minimum priority of the thread : 1
The maximum priority of the thread : 10
// The higher the priority thread The greater the probability of priority execution
Method to get thread priority :
int getPriority()
How to set thread priority :
void setPriority(int newPriority)
The guardian thread
void setDaemon(boolean on) : Pass in true Set to daemons
Method of thread hibernation
static void sleep(long millis) : Let the thread sleep -> How long to sleep depends on the incoming millisecond value
Sleep : The thread object simply releases CPU The enforcement of , Do not release lock resources
Thread security issues
As long as there are multiple threads operating on shared data at the same time , There must be a thread safety problem !!!
How to solve the case of buying tickets at the railway station : locked
Synchronous manipulation is sure to solve all the security problems in the case of multithreading
Synchronous operation
Synchronous operation : Lock means lock
The characteristics of the lock object :
1. only
2. Can control all thread objects
3. The element used for locking must be a reference data type -> Give priority to recommend : Object
The synchronized code thread object must be executed :
1. CPU The enforcement of
2. Lock resource
Synchronization code block
Format :
synchronized( Lock object ){
// Code that needs protection
}
Synchronization method
Format :
Method modifier synchronized return type Method name ( Parameter list ){
Method body ;
//return;
}
The lock object of the normal member synchronization method is this
Who is the lock object of the static synchronization method ? Bytecode objects of this class .class object
Lock Interface ( Lock in an object-oriented way )
Lock There are 2 A way :
void lock(): locked
void unlock(): Unlock
Implementation class : ReentrantLock
The life cycle of a thread
NEW : newly build -> The thread object is created but not called start
BLOCKED : Blocking -> The thread is awake but has no lock resources or no CPU Executive power
TIMED_WAITING -> Wait for a limited time
scene 1 : The thread object is called sleep( Millisecond value ) -> sleep: Just lose CPU Executive power , Have lock resources
scene 2 : The thread object is called wait( Millisecond value ) -> wait: Lost lock resources and CPU Executive power
WAITING -> Wait indefinitely
scene : The thread object is called wait() -> Only by waiting to be awakened can we revive from the infinite waiting state
RUNNABLE : function -> Have CPU Executive power , Have a lock object Executing thread object
TERMINATED : Death -> Thread state that has died

Methods of waiting and waking up
The method of waiting and waking comes from Object class
Generally, lock objects are used to control the execution of threads !!
Wake up the way : Just wake up the thread , When the thread wakes up, it still needs to rob CPU Resources and lock resources
void notify() : Wake up one at random " A dead sleep " Thread object for
void notifyAll() : Wake up all " A dead sleep " Thread object for
Waiting method : wait : Release the lock and CPU resources
void wait() : Wait indefinitely Not called notify The serial method thread will not wake up
void wait(long timeout) : Wait for a limited time It's time to wake up or be awakened in the middle
void wait(long timeout, int nanos)
Wait for the wake-up mechanism
Wait for the wake-up mechanism / Thread communication / Producer and consumer case
Customer thread , Chef thread , Steamed buns ( Lock object , Control thread execution )
边栏推荐
- SCP remote copy command record
- dhu编程练习
- Encapsulate a complete version of the uniapp image and video upload component, which can be used immediately, switch between images and videos, customize the upload button style, delete the button sty
- Using face_ Recognition library reports an error reason: cudnn_ STATUS_ NOT_ SUPPORTED
- 当大学毕业感到迷茫怎么办?
- Global communication infrastructure faces apt, robotics and DDoS; The weakest mobile network
- 搞透AQS原理(流程图及同步队列图解)
- Unity2d-- add keys to animation and bind events
- Restore a 35k-55k Tencent Android Senior Engineer Interview
- dhu编程练习
猜你喜欢

005_ button

004_ icon

搞透AQS原理(流程圖及同步隊列圖解)

【自然语言处理】【多模态】OFA:通过简单的sequence-to-sequence学习框架统一架构、任务和模态
![[MySQL 04] use MySQL workbench 8.0 CE to back up and restore MySQL databases in Linux](/img/e7/fc2925a10ac5fb370dd221c3f4a46a.png)
[MySQL 04] use MySQL workbench 8.0 CE to back up and restore MySQL databases in Linux
![[graph neural network] overview of graph classification learning [2]: graph classification based on graph neural network](/img/5f/b23b64eed7f28ffd92c122b6859e2d.png)
[graph neural network] overview of graph classification learning [2]: graph classification based on graph neural network

006_ radio

C language I want to pass

Add a second network card (network interface NIC) for the virtual machine in azure portal in 2 minutes

ROS Bridge 笔记(01)— apt 安装、源码编译安装、安装依赖、运行显示
随机推荐
Understand AQS principle (flow chart and synchronous queue diagram)
Large scale DDoS attacks and simulated DDoS tests against VoIP providers
7 — filter
CheapSwap 协议的诞生
Geotools: common tools for mutual conversion of wkt, geojason, feature and featurecollection
Matlab 2012a drawing line segment with arrow
209. minimum length subarray - sliding window
208. implement trie (prefix tree) - attach detailed notes
封装一个完整版的uniapp图片和视频上传组件,拿来即用,可进行图片视频切换,可自定义上传按钮样式,删除按钮样式,可单独上传图片或者视频,可限制上传数量
Matlab 2012a 绘制带箭头的线段
Realization of a springboard machine
Summary of DOM
【MySQL 04】使用MySQL Workbench 8.0 CE 備份及恢複Linux中的MySQL數據庫
[machine learning Q & A] cosine similarity, cosine distance, Euclidean distance and the meaning of distance in machine learning
Let‘sPlayCurling
Illustration Google V8 19: asynchronous programming (II): how does V8 implement async/await?
Is it safe to open an account in Sinosteel futures?
[protection mode] segment descriptor
scp远程拷贝命令记录
假离婚变成真离婚,财产怎么办