Core Java 10~12 (multithreading & I/O & network Programming)

Source: Internet
Author: User

MODULE Ten Threads Multithreading
--------------------------------

Process: The task unit in the process of running a computer, the CPU can only execute one process at a time, but the principle of time slicing is used in a time period.

Characteristics:
Each process executes with a separate data space, allocates memory independently, and the resources between multiple processes are not shared. So the process is very resource-intensive


Thread: Is the smallest execution unit when the program is run


Characteristics:
1) thread dependent on process
2) A process can be divided into multiple threads example: QQ
3) * Multithreading can share resources

Multi-process and multithreading are designed to perform multiple tasks at the same time

Problems with Multithreading:
concurrency (mutex) and synchronization between multiple threads (issues raised by shared resources)

Threading Class Thread

To create your own thread
1. Inheriting the thread class
Class MyThread extends thread{
public void Run () {
Thread-handling code
}
}
Use:
MyThread th1=new MyThread ();
Th1.run ();//Error
Th1.start ();//Start the thread and execute the code in the Run () method
2. Implement the Runnable interface
Class MyThread implements runnable{
public void Run () {
Thread-handling code
}
}
Use:
MyThread th1=new MyThread ();
Th1.start ();//Error
Thread thread=new thread (TH1);
Thread.Start ();//Start thread, execute the Run () method in Th1


Practice:
Turtle Rabbit Cat Dog Hundred meter race, requirements: As long as there is a first run to the end, the game is over

Analysis: Set up data that is shared by multiple threads
Static Boolean isrunning=true;


Status of the thread life cycle:
1.Runnable Ready State
New-->start ()--Runnable
Wait for the JVM to dispatch execution
2.Running status
JVM takes time Shard policy, the dispatched thread enters running state from runnable
Executes the code in the Run () method, and once the time slice has ended, the JVM will retract the execution of the thread and dispatch other threads in the runnable state, regardless of whether the run () method is executed.
Runnable <-----> Running

3.Dead Death Status
Run () method execution ends

4.Blocked Blocking status
1) Sleep ()---> Blocked
Wait until the end of the sleep time, the thread from bloced---> Runnable, waiting for the JVM to reschedule
2) Join ()---> Blocked
Call the Join () method of another thread to put the threads into a blocking state until the end of another thread execution, blocked---> Runnable


Multi-threaded concurrent access
----------------------------------
Multiple threads sharing data raises concurrency issues

Practice:

How do I resolve concurrent access?
Synchronized keywords
1) Look for public objects and lock on public objects to ensure that only one thread can manipulate the object at a time
Synchronized (Object) {
Only one thread is allowed to execute this part of the code
}
2) precise control of the lock range (or the critical value of the lock), otherwise affect the program efficiency


How threads return to runnable state from locked
------------------------------------
1) Sleep sleeping time is over, back to runnable
2) Join () wait for the other thread to finish, and return to runnable
3) How to make threads from blocked------> Runnable
A) interrupt ()
Man-made threading from blocked------> Runnable
Once the blocked thread wakes up by calling the interrupt () method, it throws Interruptedexception, and the thread itself can know that it is interrupted by catching the exception
b) isinterrupted () returns the Boolean type to determine if the thread is interrupted
c) interrupted () clears the interrupt information, because a thread is interrupted after the flag information is set, isinterruped () is determined to be true, once the call interrupted () clears the interrupt information, isinterruped () judgment changed to False

Exercise: Threadstate.java, after monitoring another thread in the main thread to let the thread sleep, call the interrupt () method to return it from blocked to runnable

Thread Synchronization Issues
-------------------------------------
Concurrency: Multiple threads are equal, competing for access to public objects, only one thread at a time

Synchronization: Resolves the sequential issue of access to public objects by multiple threads

The idea of solving the synchronization problem:
1) Identify public objects, and multiple threads communicate through public objects
2) Find out which thread is the wait and which thread is responsible for notify notification
3) Make sure Wait is before notify
Add Flag variable haswait, the waiting thread sets the variable before calling wait (), and the thread responsible for sending the notification determines the variable before notify () to ensure that the thread that has wait on the public object is notify


Practice:
Define a thread Calculatethread, calculate the 1~100 and put the result in an object
Define a thread printthread, remove the result from the object and print the output
Define a test program Test.java

Analysis:
1) is a sync issue
2) public object Result{int value;}
3) Calculatethread is responsible for notify,printthread wait


Note the point:
1.wait () and notify () to add synchronized
Multiple threads compete for access locks on public object res, and are mutually exclusive between waiting threads
2. The waiting thread must set the flag variable before wait, otherwise the wait is blocked and cannot be set
3. Notify the thread before notify to cycle to determine whether the public object has a waiting thread, there is wait line friend notification wake up
4.while cycle must be put synchronized outside, or hold the lock and sleep, other threads will never get access to the Res object

SetPriority () Set the priority of the thread 1~10 level priority does not determine the order in which the threads are executed, and ultimately is still determined by the JVM

Thread.yield () gives execution to a thread with a higher priority than its own

Deprecated methods:
Stop ()/Resume ()/suspend ()
When these methods are called, the locks on the resources occupied by the thread are not freed


Deadlock problem
------------------------------
If the main route to compete with limited resources, require simultaneous access to multiple public resources, due to the limited number of public resources, can not meet the needs of all the threads, each thread only to get some resources and not released, resulting in deadlock problems

The problem of dining philosophers

How to solve?
Let the threads of multiple competing resources get in the same order

MODULE I/O input/output
------------------------------------
The concept of flow in Java is to create a stream object between the application and peripherals, ensuring that no matter what the peripheral device is, the application only accesses the stream object to read and write data.

According to the direction of the flow, divided into:
Input stream InputStream
The program reads data from the input stream, but cannot write
Read () ...
Output stream OutputStream
The program "writes" data to the output stream, but cannot read
Write () ...

Transmission units by stream
BYTE stream
Bytes are the basic transmission units, byte transfers
Note the point:
1) data in the stream does not have a structure, example int data 4 bytes, split into 4 transmission
2) The final transmission to the peripheral device must be a byte stream
The stream ends with a byte stream *

Character Stream
Byte readability is poor, character stream provides text to read and write data
Usually with Reader/writer is a character stream *

Stream with cache capability
Set the buffer in the stream object, the data is placed in the buffer, and then read and write the peripheral device
Objective: To improve the transmission performance of data

Filter filters
Data provided in the convection for further processing
Byte stream no structure, filter can be bytes in the stream into the data type required by the application, such as int double float ...
* Cannot be used alone, be sure to combine a certain byte stream


Common methods of InputStream
Read () returns one byte at a time, returns the result >=0 as valid data, 1 indicates that the data in the stream has been read
Read (byte[]) can fetch multiple bytes at a time, put in byte[] array, return the number of bytes read successfully

Attention:
I/O flow to interact with peripherals, all resources are recycled manually
finally{
Add a resource recycling code
}

Close () Closes the stream object, freeing the memory resource
Available () determine if the stream is available

Flush () program forces the data in the cache to be flushed to the peripheral device

Hierarchical structure of Byte stream
-------------------------
Usually the Inputstream/outputstream represents the data source or data destination type
FileInputStream to read data from a file as a data source
FileOutputStream file as a data destination and write data to the file

PipedInputStream Pipe as the data source
PipedOutputStream the pipeline as a data destination

Filter further packaging of the byte stream
1) Bufferedinputstream
Stream with cache capability
2) Pushbackinputstream
Back up the data read from the stream
3) DataInputStream
The ability to spell bytes in a byte stream into the basic data type required by the program
ReadInt (0 readdouble () ...

Package: java.io;
Exception: IOException

Exercise: Creating a copy of a class Copy.java implementation file
Copy the contents of one file to another file

Analysis: Read data from source file, FileInputStream read ()
Write to destination file FileOutputStream write ()


Retrofit: In a way that improves performance


Example: To improve the performance of the way from the specified file Ah src.txt read content containing the basic data type

Analysis:
DataInputStream dis=new DataInputStream (New Bufferedinputstream (New FileInputStream ("Src.txt"));

Exercise: Writing an int integer to a file
1) Transfer one byte to 4 bytes
2) DataOutputStream (Bufferedoutputstream (FileOutputStream))


Pipe Flow Pipedinputstream/pipedoutputstream
-----------------------------------------------
PipedInputStream reading data from the pipeline
PipedOutputStream writing data to the pipeline
Connecting the input and output streams through a pipeline

Practice:
Create two threads to implement two-thread data transfer through a pipeline stream
A thread sender is responsible for generating 100 random numbers and writing to the pipeline
A thread fetcher is responsible for reading the data from the pipe and printing the output

Analysis; class Sender extends thread{
PipedOutputStream POS;
public void Run () {}
}
Class Fetcher extends thread{
PipedInputStream PiS;
public void Run () {}
}


Character Stream Reader/writer
------------------------------
Byte stream readability is poor, character stream provides text transfer data

Special Stream objects
1.bufferedrreader/bufferedwriter
1) Open buffer to improve transmission performance
Similar to Bufferedinputstream (BIS)/bos
2) provides conversions between character streams and strings
Similar Dis/dos
Bufferedreader:readline () Character stream---> string
Bufferedwriter:write (String,off,len) string----> character stream

2.inputstreamreader/outputstreamwriter Bridge Class
A byte stream that eventually interacts with the peripheral device
1) provide conversion between byte stream and character stream
InputStreamReader: Byte stream-----> character stream
OutputStreamWriter: Character stream----> byte stream
2) provides conversion between Java standard encoding UTF8 and other encodings

3.filereader/filewriter is a subclass of Inputstreamreader/outputstreamwriter
1) Ability to read and write files
2) as a subclass of ISR/OSW, it also provides conversions between the byte stream and the character stream
3) automatically convert the encoding to the corresponding encoding format of the operating system

Practice:
Writes a string to the file, then reads the file and outputs the content to the console

Analysis:
String---> File
String----> Character Stream buffredwriter
Character stream byte flow OutputStreamWriter FileWriter
byte stream file FileOutputStream
File-----> Console

System.out Standard Output
System.in keyboard
System.err standard Error


Serialization of Objects Objectinputstream/objectoutputstream
------------------------------------------------------------
Serialization: Converts an object to a stream of bytes, typically used to hold the object's current state information
Persist an object for future recovery of the object
Deserialization: Byte stream-----> Object

Objectinputstream:object ReadObject () {} deserialized
Objectoutputstream:writeobject (Object) serialization

Serialization Implementation Interface:
Serializable

Class Company implements Serializable{
String name;
int tel;
Transient Address add; Callout This attribute information cannot be serialized
}
Class address{
String City;
String Street;
int no;
}

Attention:
1) Large objects contain small objects that require small objects to implement serialization interfaces when serializing
2) for an attribute that cannot be serialized, it needs to be decorated with transient

Exercise: Objecttest.java


Randomaccessfile Random Access files
-----------------------------------
Read and write to any part of the file in random access mode

Skip (Long) is a skip step, but it also skips a few bytes from the beginning to read and write.

Function:
1) implements the Datainput/dataoutput interface, similar to the filter
2) Read/write function has
ReadInt () Writeint () ...
3) ability to manipulate files
4) You can jump to a location in the file to start reading and writing

Parameters in the constructor:
mode specifies the read/write pattern
"R": Read Only "R": Write Only "RW": Read/write

Seek (long) skips a long specified number of bytes and begins to read and write


MODULE Network Programming
--------------------------------
IP address can be uniquely located to a machine on the network via an IP address
Port ports: Artificially manufactured numbers that represent the unique identity of an app on a server

Network programming based on TCP/IP
Transmission Control Protocol, considering the reliability of transport issues
Network programming based on UDP
User Data message Protocol, considering the efficiency of the transmission problem

Five elements of communication between the two sides:
1. Communication between the two IP addresses (two)
2. Port port number (two) for both sides of the communication
3. The communication Parties shall abide by the same agreement

java.net Package:
Socket/seversocket: Implementing TCP/IP-based network programming
Datagramsocket/datagrampacket: Service for UDP protocol

IP network layer
Basic Features:
no connection; Data reliability is not guaranteed;

TCP Transport Layer
1) connection-oriented
2) Complete and reliable data transfer
3) Point-to-point
4) The same connection can be sent or received
5) byte-stream-oriented

The connected resume has been shook three times:
1) The client makes a connection request
2) Server reply acknowledgement
3) Establish a connection


Client:
Build the socket to connect the specified IP and port
---> Get input stream/output stream
--Wrapping the I/O stream
----> read/write Data
Free Resources (SOCKET/I/O)

Server:
Building Seversocket, specifying the port number for listening
---> Receive client connection request, get socket establish connection
----> Packaging of I/O streams
----> read/write Data
Free Resources (SEVRVERSOCKET/SOCKET/I/O)


PrintWriter function
String--> Byte stream
BufferedWriter Strings---character streams
OutputStreamWriter character Stream---> byte stream
1. String---> Byte stream
Combines the functions of both bufferedwriter/outputstreamwriter
2. can automatically refresh
New PrintWriter (os,true);


UDP User Data Message Protocol
-------------------------------------------
1) Consider the efficiency of data transmission, reliability is not guaranteed
2) Not necessarily a one-to-many communication, such as broadcasting
3) non-connected, unreliable transmission mode

Datagramsocket responsible for sending and receiving data such as the Postman
Datagrampacket data into a Message object, fill in the other's IP address and port number such as letters

Constructor:
Datagrampacket ()

Core Java 10~12 (multithreading & I/O & network Programming)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.