Introduce Java threads, threads and Runnable

xiaoxiao2021-03-06  83

Get excellent performance (i) - introducing threads, threads and Runnable Jeff Friesen

Summary

User expectations can show excellent performance. To meet this expectation, your program is often used in threads. In this article we started practicing using threads. You will learn threads, threads, and runnable.

Users don't like software that is slow. When a user clicks on a mouse, they hope that the program immediately responds to their request, even if the program is in the time of operation, such as a very long document re-edited page number or waiting for a network operation. Procedures for users in response to users are poor. In order to improve program performance, developers generally use threads.

This article is the first part of the exploration thread. Although you may think thread is a thing that is difficult to master, I intend to show you that thread is easy to understand. In this article, I will introduce you to threads and threads, and discuss Runnable. In addition, in the later article, I will explore synchronous (by lock), synchronous issues (such as dead locks), waiting / notify mechanisms, timing arrangements (priority and no priority), thread interrupts, timers, volatile Sex, thread groups and thread local variables.

Read the entire series of thread design:

· Part 1: Introduce threads and threads, and Runnable

· Part 2: Use synchronization to enable thread serialization to access key code part

note

This article and the three related thread exercises in its app are different from applets. However, I am using most applications introduced in the app to Applets. The main difference is: For safety reasons, not all thread operations can be placed in an applet (I will discuss Applets in later articles).

What is thread?

The concept of thread is not difficult to grasp: it is a separate execution channel of the program code. When a plurality of threads are executed, the channels of one thread via the same code are usually different from others. For example, it is assumed that one thread executes byte code that corresponds to the IF portion of an IF-ELSE statement, and the other thread is performing byte code equivalent to the ELSE portion. How does JVM keep track of each thread? JVM calls the stack for each thread itself. In addition, track the current command byte code, the method stack tracks the local variable, the JVM passes to a method of parameters, and the return value of the method.

This behavior is called multi-thread when multiple threads perform byte code sequences in the same program. Multi-threading is conducive to procedures:

• Multithreading GUI (Graphical User Interface) program can still maintain a response to the user, such as rebuilt page number or print a document.

· The program with threads is generally completed faster than those who have no threads. This especially performance is running on a multiprocessor machine in a multiprocessor machine, and every thread has its own processor.

Java completes multithreading through the Java.lang.Thread class. Each thread object describes a separate execution thread. Those run () methods that run in the thread. Because the default Run () method does not do, you must create a Thread subclass and overload Run () to complete useful work. Exercise List 1 gadgets a thread and multi-thread in Thread:

List 1. ThreadDemo.java

// ThreadDemo.java

Class ThreadDemo

{

Public static void main (string [] args)

{

Mythread MT = new mythread ();

Mt.start ();

For (int i = 0; i <50; i )

System.out.println ("i =" i ", i * i =" i * i);

}

Class mythread extends thread

{

Public void Run ()

{

For (int count = 1, row = 1; ROW <20; Row , Count )

{

For (int i = 0; i

System.out.print ('*');

System.out.print ('/ n');

}

}

}

Listing 1 shows the source code for applications consisting of THReadDemo and MythRead. Class ThreadDemo starts a thread related to its object and executes a code that prints a square table. Instead, Mythread is overlighted with Thread's Run () method prints (by standard input stream) a right angle triangle composed of star symbols.

When you type Java ThreadDemo running an application, JVM creates a start thread that runs the main () method. By performing Mt.Start (), start thread tells the JVM to create a second thread that executes the byte code instruction of the Run () method containing the Mythread object. When the start () method returns, the start thread loop performs printing a square table, at which time another new thread performs a Run () method prints the right triangle.

What is the output? You can see it running ThreadDemo. You will notice that the output of each thread is alternate with each other. Such results are because the two threads send their output to the same standard output stream.

note

Most (not all) JVM devices use the thread performance of the lower platform. Because those performance is a platform-specific, your multi-threaded output order may be different from the order of other people's other outputs. This difference is due to timing arrangements, I will discuss this topic later.

Thread class

To read multithreaded code, you must first understand a variety of ways to create a Thread class. This method will explore these methods. Clearly, you will learn how to start threads, name your thread, make threads sleep, decide if a thread is activated, associate a thread with another thread, and list all activation in the thread group and subgroups in the current thread the rout. I will also discuss the contrast of thread debug assist procedures and user threads and supervision threads.

I will meditate on the remaining part of the thread method in the later article, except for the way Sun does not agree.

caveat

Sun has some unidentified thread types, such as suspend () and resume () because they can lock your programs or destroy objects. So, you don't have to call them in your code. Considering the SDK files for these method workspaces, I don't include these methods in this article.

Construct thread

THREAD has eight constructors. The simplest is:

Thread (), create a Thread object with a default name

· Thread (String Name), create a Thread object with the name of the specified Name parameter

The next simplest constructor is Thread (Runnable Target) and Thread (Runnable Target, String Name). These constructors are the same as those described above in addition to the RunNable parameters. Different: the runnable parameter identifies an object other than the thread of the RUN () method. (You will learn Runnable later in this article) The last few constructors are Thread (String Name), Thread (Runnable Target), and Thread (Runnable Target, String Name). However, the final constructor includes a ThreadGroup parameter for organizing intent. One of the last four constructors, Thread (ThreadGroup Group, Runnable Target, String Name, long stacksize), is interested in making you specifying the size of the thread method calling the stack. It is very helpful to specify that the size will prove that in the use of the recursive method (a technique whose method is constantly repeating itself), it is very helpful. By explicitly set the stack size, you can sometimes prevent STACKOVERFLOWERRORS. However, too general leads to OutofMemoryErrorS. Similarly, Sun will call the size of the stack as a platform dependence. Dependent platform, method calls the size of the stack may change. Therefore, you carefully consider your program branches carefully before Write THREAD (ThreadGroup Group, Runnable Target, String Name, long stacksize).

Start your load tool

Threads are similar to the vehicle: they move the program from the beginning to the end. Thread and Thread subclass objects are not threads. They describe the properties of a thread, such as name and code containing threads (via a RUN () method). When a new thread performs Run (), another thread is positively: the start () method of the Thread or its subclass object. For example, to start the second thread, the application's start thread - it performs main () - call start (). The thread operation code that is operated with the JVM and the platform ensures that the thread correctly initializes and invokes the RUN () method of the Thread or its sub-object.

Once START () is complete, multiple lines are running. Because we tend to think in a linear way, we often find that it is difficult to understand concurrency (simultaneous) behavior when two or more threads are running. Therefore, you should look at the chart showing the display and time to perform (its location). The picture below is such a chart.

With time compare a behavior of starting thread and a new thread execution location

The chart shows several important period:

· Start the initialization of threads

· Thread starts to execute main () instant

· Thread starts to perform start () instant

· Start () creates a new thread and returns the moment of main ()

· Initialization of new thread

· The new thread began to perform the moment of Run ()

· Different moments of each thread end

Note that the initialization of the new thread, is the execution of Run (), and its end of its end occurs simultaneously with the start thread.

caveat

After a thread calls start (), when the Run () method exits, the method will cause start () to throw a java.lang.illegalthreadStateException object.

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

New Post(0)