Multi-thread programming, Java Network Programming, and multi-thread programming

Source: Internet
Author: User

Multi-thread programming, Java Network Programming, and multi-thread programming

1. Thread Overview

There are two types of multi-task processing: process-based and thread-based (process refers to a self-contained running program with its own address space; A thread is a single sequential control flow in a process)

The process-based feature allows the computer to run two or more programs at the same time. In a thread-based multi-task processing environment, the thread is the smallest processing unit.

2. Create and start a thread

A. method for creating A thread:

A. Compile a class that inherits the Thread class, and then override the run () method of the Thread class.

Public class thread extends Thread {

Public void run (){

}

Public static void main (String [] args ){

Thread d = new thread ();

D. start ();

}

}

B. Compile a class to implement the Runnable interface, and associate the instance of the class with the Thread object.

Public class threadrun implements Runnable {public void run (){

}

Public static void main (String [] args ){

Threadrun td = new threadrun ();

Thread t = new Thread (td );

T. start ();

}

}

3. thread priority

A. The Thread priority in Java is A constant defined in the Thread class:

NORM_PRIORITY: The value is 5.

MAX_PRIORITY: The value is 10.

MIN_PRIORITY: The value is 1.

B. There are two methods for priority:

A. final void setPriority (int newp): modifies the current priority of a thread.

B. final int getPriority (): return the priority of the thread

4. Conditions for pausing a thread

A. Use sleep () to sleep the thread

B. wait the thread by calling the wait () method

C. By calling the yield () method, the thread has explicitly granted control over the CPU

D. The thread is blocked because it waits for an I/O event.

5. Thread Synchronization: Use the synchronization keyword synchronized.

A. Solution to thread synchronization:

A. Synchronization Block

Syntax: synchronized (the object that gets the lock ){

// Code to be locked

}

B. Synchronization Method: Use synchronized before modifying the method name keyword.

6. deadlock: a deadlock occurs when two threads cycle on a synchronization object.

7. Mutual Communication between threads

Method:

A. wait (): notifies the called thread to exit the monitor and wait until other threads enter the same monitor and calls the notify () method B. Y (): notifies the same object of the first wait () thread C. yyall (): notifies all threads that call wait (). Threads with the highest priority will run first. 8. OSI model: ISO provides an OSI reference model, which divides networks into seven layers. 9. TCP/IP protocolA. Addressing and locating of programs on the network host

A. The essence of network programming is to write programs to communicate directly or indirectly with a program on other computers through network protocols.

B. How can I find the program for communication on the host on the network?

C. You can find the specified program for communication on the specified host on the network by providing the IP address and port number.

B. Port: used for inter-program communication C. How to transmit data to a program on the host on the network?

A. data transmission is performed by the transport layer in the TCP/IP layered model. The layer includes TCP and UDP protocols.

B. TCP protocol: reliable two-way stream protocol, sending any amount of data, providing message confirmation, error detection, error recovery, and other services

C. UDP protocol: relatively unreliable

10. clients and servers

A. servers and clients share computing

A. Customer: The computer requesting services from another computer

B. SERVER: The computer that processes client requests

11. Socket: The End of Internet communication. The client and server establish a connection and communicate with each other through the Socket. 12. Java's support for Network Programming

The pre-defined network programming classes of JDK are all stored in the java.net package.

Common classes: InetAddress, Socket, ServerSocket and SocketImpl, DatagramPacket and DatagramSocket, URL, URLConnection, and URLEncoder

A. InetAddress class: Used to encapsulate the IP address and DNS of A computer

This class has no constructor, so you cannot directly use the new keyword to create an object. We can use the following common methods to obtain such objects:

GetLocalHost (): indicates the InetAddress object of the local host.

GetByName (String hostName): returns an object based on the host name.

GetAddress (): IP address returned

GetHostName (): Get the host name represented by the IP address

13. TCP socket programming

Two java programs exchange data through a two-way network communication connection. one end of this two-way link is called Socket (Socket is usually used to achieve the connection between the client server)

The two types of Socket and ServerSocket in the java.net package are used to implement the client and server respectively.

A. Server (ServerSocket) Writing steps:

1). Use ServerSocket to establish a listener for a port on the server.

2). Use the accept method to create a server Socket

3). Use a socket to create an input/output stream

4). Disable the input/output stream, socket, and server.

B. Write a Socket:

1) create a client Socket to initiate a connection request to the server

2). Use a socket to create an input/output stream

3). Close the input/output stream, socket, and server.

14. UDP socket programming

A. User Message Protocol (UDP) is A non-connection protocol used to send binary data from one computer to another.

B. Both the sender and receiver of the datagram packet use the java.net. DatagramSocket class to send and receive packets respectively.

The send () and receive () Methods of the C. initramsocket class both carry an initrampacket parameter. The mongorampacket class represents a datagram packet. Similar to the mongoramsocket class, both the packet sender and receiver must use it.

D. To receive a datagram package, perform the following steps:

1) create a large enough byte array to store the data of the packet to be received

2) use this byte array to instantiate a DatagramPacket object.

3). The initramsocket is instantiated and is specified as a port on the local host to which the socket is bound.

4) Call the receive () method of the initramsocket class to pass in the initrampacket object. This will cause execution thread blocking until a datagram packet is received or timeout occurs.

E. To send a data packet, follow these steps:

1) create a byte array that is large enough to store the package data to be sent and fill the array with the data.

2) create a new initrampacket object to store the byte array and the server name and receiver port number.

3). The initramsocket is instantiated. It is specified which port of the socket to bind to the local host.

4). The send () method of the initramsocket class is called and an initrampacket object is passed in.

 

Example: simple LAN chat system-lan QQ:

Server

This allows you to easily start and stop server operations and record basic logs: Customer connection, message transmission, and nickname of connected customers.

After the server is started, start listening to the client connection and create a new thread to implement this listening operation.

// Start a new thread to listen to the client

New Thread (new Runnable (){

Public void run (){

WriteLog ("start listening to the client :");

Listen ();

}

}). Start ();

Enable a new thread for each client connection to process communication, including processing input and output streams.

// Start a new thread to process each client connection that is listened

New maid (this, socket, usersList). start ();

Obtain different user behaviors and perform different operations. String flag = in. readUTF ();

// Obtain user operation Behaviors

If ("validateUser". equals (flag) {// verify whether the user exists

//........................

} Else if ("newUser". equals (flag) {// New User Login

//........................

} Else if ("message". equals (flag) {// send messages between users

//........................

} Else if ("userList". equals (flag) {// get the user list

//........................

}

On the server side, Map is used to save the socket corresponding to each client:

Private Map <String, Socket> usersList = new HashMap <String, Socket> ();

The key is the user nickname input during client connection, and the value is the corresponding socket object.

When sending messages between client users, this information is forwarded through the server:

String sender = in. readUTF (); // sender

String receiver ER = in. readUTF (); // recipient

String message = in. readUTF (); // message

// Add logs

Server. writeLog (sender + "send message to" + receiver Er + ":" + message );

// The server forwards messages to the target socket object. The target socket object to be forwarded is obtained first.

Socket socket = server. getUsersList (). get (receiver );

System. out. println (out );

If (socket = null) {// the server has deleted the client connection information

Out. writeUTF ("message ");

Out. writeUTF ("system server ");

Out. writeUTF (the Consumer Er + "has exited the system and cannot send messages again ");

Out. flush ();

} Else {

DataOutputStream thatOut = new DataOutputStream (socket. getOutputStream (); // create an output stream object

If (thatOut! = Null ){

ThatOut. writeUTF ("message ");

ThatOut. writeUTF (sender );

ThatOut. writeUTF (message );

ThatOut. flush (); // write to the client output stream

}

}

 

Client

First, use the login form to connect to the server, and then enter the nickname of the login user. If the nickname is not saved on the server, the login is successful. After successful logon, you can read the nickname of an existing logon user on the server and display it in the list. Double-click any item in the friend list to open the chat dialog box. Then, both parties can start chatting.

Socket object created on the server:

// Create a socket object

Socket = new Socket (serverIp. getText (). trim (), Integer. parseInt (port. getText (). trim ()));

The Connected Server and port are obtained from the form text box.

After successfully logging on to the server, send the nickname to the server for saving:

Out. writeUTF ("newUser ");

Out. writeUTF (nickname); out. flush ();

Refresh the friend list:

// Read the information in the stream

String flag = in. readUTF ();

If ("userList". equals (flag) {// friend list

String [] userList = in. readUTF (). split ("::::"); // obtain the friends list, which is separated by tags.

// Create a friend list Model

DefaultListModel list = new DefaultListModel ();

For (int I = 0; I <userList. length; I ++ ){

List. addElement (userList [I]);

}

Friends. setModel (list); // sets the Model

Friends. validate (); // redraw

}

Send a message to a friend:

Out. writeUTF ("message ");

Out. writeUTF (sender );

Out. writeUTF (recipient );

Out. writeUTF (textArea. getText ());

Out. flush ();

Enable a new thread to read the server-forwarded friend information:

String flag = in. readUTF ();

If ("message". equals (flag )){

String sender = in. readUTF ();

String msg = in. readUTF ();

String message = sender + "to you:" + msg + "\ n ";

JTextArea. append (message );

}

 

Related Article

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.