Java multi-thread programming preliminary

zhaozj2021-02-16  65

What is multi-thread programming multi-thread programming technology is an important feature of Java language. The meaning of multi-threaded programming is to divide the program task into several parallel sub-tasks. Especially in network programming, you will find that many features can be executed concurrently. For example, the network transmission speed is slower, the user input speed is slow, you can use two separate threads to complete these two features without affecting normal display or other functions.

Multithreading is compared with single-thread, ordinary Windows adopts a single-threaded program structure, its working principle is that the main program has a message loop, constantly reading the message from the message queue to determine the next step to do, general It is for a function, only after this function is executed, the main program can receive additional messages. For example, the sub-function function is to read a network data, or read a file, only wait for this data or file to receive the next message. You can't do anything during this subunies. But often read network data and waiting for user input, there are many times, and multithreading uses this feature to divide the task into multiple concurrent tasks, you can solve this problem.

The thread class in Java learns to learn multi-threaded programming in Java, you have to know how to implement a multi-thread class. There are two ways to implement multithreaded classes in Java:

1. Expand the Java.lang.Thread class to override the RUN method of the Thread class.

2. Generate classes that implement the Java.lang.Runnable interface and associate additional instances with the java.lang.Thread instance.

The THREAD class is the most important class responsible for providing thread support to other classes. To use a class with a thread function, you can expand the Thread class as long as you have a subclass from the Thread class from the Thread class, such as PrintThread.java.

Below we will introduce how to use these two methods to write their own multi-threaded applications.

Create subclasses for java.lang.thread class

The most important way to THREAD is the RUN method. The RUN method is a method of new thread execution, thus generating a subclass of java.lang.Thread, must have a corresponding RUN method.

//Printthread.javapublic class printthread extends thread // Inherited Tread class private int count = 0 // Define a count variable for statistical printing times and shared variables public static void mainstring  args  // main Method Start PRINTTHREAD P = New PrintThread   // Create a thread instance P.Start   // Execute thread for {;;}  // Main thread main method Perform a loop, for execution a dead cycle count System.out.printcount ": main / n"  // main thread count print value "main" variable, and wrap public void run // thread must be some kind Run () method for {;;} count system.out.print count ": thread / n"  

 The above program is to inherit java.lang.tread and override the RUN. When starting a program with a Java virtual machine, this program will be a thread and call the main MAIN method of the program. The main method in this program generates a new thread and connects "Thread". After starting the thread, the main thread continues to print "main". Compile and execute this program, then press the Ctrl C key to interrupt the program, you will see the two threads described above continue to print out: XXX: main ... ..xxx: thread .... xxx represented numbers That is, the value of the top of the top. On the author's machine, the number of times the two threads in different moments is different, first print 20 main (that is, executing 20 main threads first)  Print 50 Thread, then print main ... Tip: For the sake Easy to view the execution of the program, you can import the execution result into a text file, then open this file to see the cases performed by each thread. Such as running: javac printthread.javajava printthread> 1.TXT The first command javac printthread.java is compiled Java program, the second is to execute the program and import the result into the 1.txt file. In this way, open this file, you can see the detailed result (Note: The execution time of the program cannot be too long, or the generated 1.txt file will be very large). Of course, you can execute the command directly: Java Printthread. Another way to implement a java.lang.Runnable interface Running thread is to implement the runnable interface, then generate threads running this class. The RunNable interface is an interface defined in the java.lang package, which only provides an abstract RUN declaration. Let's take a look at how to implement the runnable interface instead of extending the Thread class.

//PrintRunnableThread.java implement Runnable public class PrintRunnableThread implements Runnablepublic static void mainString argsThread t = new Threadnew PrintRunnableThread // t.setPriorityThread.MAX_PRIORITY // Set the maximum priority T.Start   // thread start for {;;}    // Stop character M, represent the main thread mainsystem.out.println  "m"     Void run    {;;}     不 字 字 字 字 字 字 字 字 字 字 字 字          代

Run this program, you will find that the execution result is similar to the execution of the PrintThread.java, and you can add a variable again and print a similar thread execution result.

Tip: Different from the previous example, if you remove the comment before the T.SetPrioritythread.max_priority  statement, set the thread to the maximum priority, and the results are bigger.

Thread group threadgroup

The Java.lang.ThreadGroup class represents a set of threads (possibly containing other THREADGROUP) to implement centralized packet management of threads in accordance with specific features. Each thread created by the user belongs to a thread group, which can be specified when the thread is created, or may not specify a thread group to make the thread among the default thread groups. However, once the thread adds a thread group, the thread has always exists in the thread group until the thread is terminated, and the thread group to which the thread belongs is not changed. The following code demonstrates how to operate and use ThreadGroup.

//Threadgrouptest.javapublic class threadgrouptest imports runnable public void runpublic static void main (string args [])                                                                                                              . ThreadGroup threadgroup = new ThreadGroup "thread group" Thread t1 = new Threadthreadgroupnew ThreadGroupTest "Thread 1" Thread t2 = new Threadthreadgroupnew ThreadGroupTest "Thread 2"  / / Find the top-level parent thread threadgroup parent = thread.currentthread  g g =     = =Parent.getParent  = null gParent = Parent.getParent   = // Get the parent thread  // list  Method prints out all contents of the current thread group  thread and subline group pparent.list  

Tip: In the upper program, the List () method displays the structure and content of the ThreadGroup tree (may include threads and thread groups, which constitutes a thread tree). Running the above program You will have a certain understanding of the thread group.

转载请注明原文地址:https://www.9cbs.com/read-17043.html

New Post(0)