当前位置:网站首页>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 )
边栏推荐
- Geotools: common tools for mutual conversion of wkt, geojason, feature and featurecollection
- Scala基础【入门及安装】
- Summary of DOM
- Openlayers 3 built in interaction
- Internet Crime Complaint Center reports an increase in DDoS Attacks
- [graph neural network] overview of graph classification learning [2]: graph classification based on graph neural network
- AI landing manufacturing: intelligent robots should have these four abilities
- 209. minimum length subarray - sliding window
- C language continues (3n+1) conjecture
- Geotools wkt coordinate system conversion
猜你喜欢
![[MySQL 05] SUSE 12 SP5 modifies the MySQL password for the first time after installing MySQL](/img/37/d24c9e5fad606d2623900ad018b6af.png)
[MySQL 05] SUSE 12 SP5 modifies the MySQL password for the first time after installing MySQL

Derivation of univariate polynomial in C language

After the blueprint node of ue5 is copied to UE4, all connections and attribute values are lost

搞透AQS原理(流程图及同步队列图解)

How to create a CSR (certificate signing request) file?

Matlab 2012a 绘制带箭头的线段

ROS bridge notes (01) - APT installation, source code compilation and installation, installation dependency, and operation display

Widget uses setimageviewbitmap method to set bug analysis
![[MySQL 06] backup and restore MySQL database in Linux + docker container environment](/img/4e/8662d15ff84b2436d02948019540d3.png)
[MySQL 06] backup and restore MySQL database in Linux + docker container environment

C language score ranking
随机推荐
scp远程拷贝命令记录
Using grpcui to test asp Net core grpc service
DHU programming exercise
Unity2d-- add keys to animation and bind events
If mybaits cannot query the data, it can query how to change it in the database
DDoS attacks - are we really at war?
什么是幂等性?四种接口幂等性方案详解!
Restore a 35k-55k Tencent Android Senior Engineer Interview
实现VS每次只运行一个源文件
003_ color
【MySQL 06】linux + Docker容器环境中备份和还原MySQL数据库
Let‘sPlayCurling
假离婚变成真离婚,财产怎么办
Is online stock trading safe? Do you need to open an account for stock trading?
dhu编程练习
9 - regular check set
Blitzkrieg companies with DDoS attacks exceeding 100gbps in 2014
DDoS surge in mobile and data centers
DDoS threat situation gets worse
8 — router