JAVA Language Programming Chapter 10 and 11

Chapter 10: threads

10.1 thread overview

  • Program is an ordered set of instructions, which is a static concept
    A process is a running program. A program runs many times to produce multiple processes, and one process corresponds to one program
    Thread is an entity of a process. It is the basic unit of CPU scheduling and dispatching. It is a smaller basic unit that can run independently than a process

  • The process is introduced to enable the program to execute concurrently, so that it can execute multiple tasks. The introduction of threads is to reduce the time and space overhead of concurrent program execution. Threads have many characteristics of processes, also known as lightweight processes. Usually, a process can contain several threads, but at least one

  • A process consists of code, data, kernel state, and a set of registers. A thread consists of registers and stacks that represent the running state of a program

  • A thread is similar to a program with a single execution flow, but the thread itself is not a program. It must run in a program (process)

  • Multithreading:

    • Multithreading refers to that a program contains multiple execution streams. It is an effective means to realize concurrency
    • The meaning of multithreaded programming is that the program task can be divided into several parallel subtasks
      • Concurrency: when there are multiple threads operating, if the system has only one CPU, it is impossible for it to carry out more than one thread at the same time. It can only divide the CPU running time into several time periods, and then allocate the time periods to each thread for execution. When the thread code of one time period runs, other threads are suspended. This method is called concurrent
      • Parallelism: when the system has more than one CPU, the operation of threads may be non concurrent. When one CPU executes one thread, the other CPU can execute another thread. The two threads do not preempt CPU resources and can be carried out at the same time. This method is called parallel
  • The thread model in Java is an encapsulation of CPU, program code and data:

    • A virtual CPU
    • Executable code (shared by multiple threads)
    • Data required for code operation (shared by multiple threads)

10.2 thread creation

  • Implement the Runnable interface to create a thread:

    • To create a thread:

      1. Define a class to implement the Runnable interface and the run() method
      2. An instance of the Runnable interface class will be implemented as a parameter of the constructor of a Thread class
      3. Start the thread with the start() method
    • //In Java The Runnable interface in Lang is defined as:
      public interface Runnable{
             void run();
        }
      
      public class ThreadText{
          public static void main(String[] args){
              Thread t1 = new Thread(new Hello());
              Thread t2 = new Thread(new Hello());
              t1.start();
              t2.start();
          }
      }
      class Hello implements Runnable{
          int i;
          public void run(){
              while(true){
                  System.out.println("Hello" + i++);
                  if(i == 5)break;
              }
          }
      }
      
  • Create a Thread by inheriting the Thread class:

    • Create steps:

      1. Subclass from the Thread class and override the run() method to define the Thread body
      2. Create the object of the subclass and start the thread through the start() method
      3. Create a Thread by inheriting the Thread class
    • //In Java Lang package, the declaration of Thread class is as follows:
      public class Thread extends Object implements  Runnable 
      public class ThreadText{
          public static void main(String[] args){
              Hello h1 = new Hello();
              Hello h2 = new Hello();
              h1.start();
              h2.start();
          }
      }
      class Hello extends Thread{
          int i;
          public void run(){
              while(true){
                  System.out.println("Hello" + i++);
                  if(i == 5)break;
              }
          }
      }
      
  • Differences between the two methods:

    • It is easy to implement with the method code that inherits the Thread class, and other methods of the Thread can be called directly in the run() method
    • Method of using Runnable interface:
      1. It is suitable for multiple threads of the same program code to process the same resource
      2. Conform to the object-oriented design idea
      3. Easy to inherit other classes

10.3 thread scheduling and thread control

  • Multiple CPUs can execute concurrently, but a single CPU can only run one thread at a time

  • Running multiple threads in a certain order on a single CPU is called thread scheduling. Java thread scheduling strategy is a priority based preemptive scheduling

  • In the Java running system, multiple thread waiting pools are set according to priority. The JVM runs the threads in the high-level priority pool first, and the low priority pool is considered only after the high-level priority pool is empty

  • Basic thread control:

    • sleep( )//You can give up the cpu to threads with low priority.
                static void sleep(int millsecond) Sleep time in ms
                static void sleep(int millsecond,int nanosecond)
               //Sleep time is milliseconds + nanoseconds
      yield( )//After calling this method, you can give a thread with the same priority as the current thread a chance to run. If there is no thread of the same level, the thread continues to run
      currentThread()//Returns the current thread
      join( )//t. The join () method makes the current thread wait, and the thread t runs first.
      interrupt()//t.Interrupt() interrupt t's blocking state
      isAlive()//Test whether the thread is alive
      
  • Thread synchronization:

//******************Three threads, only 50 tickets**********************//
public class SaleDemo {

    public static void main(String[] args) {

        SellTicket st = new SellTicket();
        Thread thread1 = new Thread(st);
        thread1.setName("Thread 1");
        Thread thread2 = new Thread(st);
        thread2.setName("Thread 2");
        Thread thread3 = new Thread(st);
        thread3.setName("Thread 3");
        thread1.start();
        thread2.start();
        thread3.start();
    }
}

class SellTicket implements Runnable {
    private int no = 0;
    public void run() {
        while(true){
        sell();
    }
}

public synchronized void sell() { // Synchronous operation and mutex lock
        if (no==50) System.exit(0);
        no++;
        System.out.println(Thread.currentThread().getName() + "Selling tickets no " + no);
    }
}

Chapter 11: network programming

  • Network programming:

    • Network programs can transmit data between two or more devices (such as computers). Compared with ordinary stand-alone programs, the biggest difference of network programs is that the programs that need to exchange data run on different computers
  • Network Communications:

    • Network communication is based on the "request response" model, that is, in network programming, one end of the communication sends data and the other end receives and feeds back data. In network communication, the program that initiates communication for the first time is called client program, and the program waiting for connection in the first communication is called server program
  • Fundamentals of network communication:

    • Application layer: http (Hypertext Transfer Protocol), ftp (File Transfer Protocol)
    • Transport layer: TCP (connection based protocol), UDP (no connection) (add port to data)
    • Network layer: IP (plus IP address)
    • link layer
    • physical layer
  • Port number in TCP/IP:

    • agreementPort number
      ftp protocol21
      Http protocol80
      Mysql3306
      Sqlserver1433
  • Java provides two different levels of network support mechanisms:

    1. Using URL to access network resources
    2. Using Socket communication
  • URL communication method:

    • The URL is described by a string. The URL includes two parts: protocol and resource name. The protocol represents the protocol required to access resources, such as HTTP, FTP, etc; The resource name indicates the address of the resource to be accessed

    • public URL(String spec) 
      public URL(URL context, String spec)
      public URL(String protocol, String host, String file) 
      public URL(String protocol, String host, int port, String file)
      //After a URL object is generated, its properties cannot be changed, but these properties can be obtained through its given method:
      public String getProtocol(): Get the URL Protocol name for
      public String getHost() : Get the URL Host name of
      public String getPort() : Get the URL Port number of
      public String getPath() : Get the URL File path for
      public String getFile() : Get the URL File name for
      public String getRef() : Get the URL Relative position in file
      public String getQuery() : Get the URL Query name for
          
      //The object of the URL class in Java represents a URL address. Examples of creating URL objects
      URL hnucm = new URL("http://www.hnucm.edu.cn/info/1094/2799.htm");
      
      URL hnucm =new URL("http", "www.hnucm.edu.cn","/info/1094/2799.htm"); 
      
      URL hnucm = new URL("http", "www.hnucm.edu.cn", 80, "/info/1094/2799.htm");  
      
    • Read URL object specified resource:

      • The openStream() method establishes a connection with the specified URL and returns an InputStream object to convert the resource at the URL into a data stream. Through this InputStream object, you can read the data in the resource

      • public class URLReader
        {    public static void main (String args[])
            {
                try{
                    URL gis = new URL("http://www.hnucm.edu.cn/info/1094/2799.htm");
                    BufferedReader in = new BufferedReader( new InputStreamReader( gis.openStream() ) );
                     String line;
                     while( (line = in.readLine()) != null ){
                           System.out.println(line);
                     }
                     in.close();
                 }
        	catch(Exception e){
                     System.out.println(e);     }
            }
        }
        
  • Socket communication mechanism:

    • Two communication modes:

      • With connection mode (TCP): at the beginning, both communication parties must conduct a connection process and establish a communication link. The communication link provides reliable, full duplex byte stream services
      • Connectionless mode (UDP): there is no connection process between communication parties. A network I/O is carried out in the form of a datagram, and each network I/O can be carried out with different processes of different hosts. The overhead of connectionless mode is less than that of connected mode, but the data transmission service provided is unreliable and can not guarantee that the datagram will reach the destination
    • Steps:

      1. Create socket and establish connection:
        • java. The two classes Socket and ServerSocket in the. Net package represent the Client side and Server side of the connection respectively. The methods for network communication are also encapsulated in these two classes. To establish a connection, first create the objects of these two classes and associate them
      2. Open the input / output stream connected to the Socket and read / write the Socket according to a certain protocol. After the connection is established, further obtain the I/O stream on the connection and transmit data through these streams
      3. Close Socket
    • Socket class:

      • //Construction method
        public Socket(String host, int port) //Host name, port number
        //common method
        //Socket input / output stream management
        public InputStream getInputStream()
        public OutputStream getOutputStream() 
        These methods will throw exceptions IOException,Capture processing is required in the program.
        //Close Socket
        public void close() throws IOException
        
    • ServerSocket class:

      • //Construction method
        public ServerSocket(int port)
        public ServerSocket(int port, int backlog): Supports the specified number of connections
        public ServerSocket(int port, int backlog, InetAddress  bindAddr)
        //These methods will throw an exception IOException, which needs to be captured and processed in the program.
        //common method
        public Socket accept(): Waiting for client connection
        public void close(): close Socket
        
  • Multithreaded TCP server:

    • Responding to connection requests from multiple clients:
      1. Start multiple server programs on one computer at a time, as long as the port numbers are different
      2. Write the server as multithreaded, and the main program listens to a port and waits for the client to access; At the same time, construct a thread class to take over the session. When a Socket session is generated, the session is handed over to the thread for processing, and then the main program continues to listen; Sockets and threads that communicate with clients can be managed on the server side, so that clients can communicate with each other with the assistance of the server side

Keywords: Java Back-end

Added by jason_kraft on Thu, 06 Jan 2022 15:29:53 +0200