Introduction Java thread, thread class and Runnable (2)

xiaoxiao2021-03-06  91

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

How to use the name

During a debug session, the user-friendly way is partially distinguished from another thread. To distinguish one of the threads, Java gives a name to a thread. Thread default name is a short-term hyphen and a zero-start number symbol. You can accept Java's default thread name or choose to use yourself. In order to be able to customize the name, Thread provides a constructor with an Name parameter and a setName (String Name) method. Thread also provides a getName () method to return the current name. Table 2 shows how to create a custom name through Thread (String Name) and retrieve the current name by calling getName () in the Run () method:

Table 2.NameThatthread.java

// NameThatthread.java

Class NameThatthread

{

Public static void main (string [] args)

{

Mythread MT;

IF (args.length == 0)

Mt = new mythread ();

Else

Mt = new mythread (args [0]);

Mt.start ();

}

}

Class mythread extends thread

{

Mythread ()

{

// Compiler Create an equivalent of the byte code in super ()

}

Mythread (String Name)

{

Super (name); // Pass the name to the THREAD super class

}

Public void Run ()

{

System.out.println ("My Name IS:" GetName ());

}

}

You can pass an optional Name parameter to mythread at the command line. For example, Java NameThatthread X establishes X as the name of the thread. If you specify a name fails, you will see the output below:

My name is: thread-1

If you like, you can change the super (name) call into setName (String Name) call in Mythread (String Name) constructor - a method for calling the same to establish a thread name as a way As a super (name) I have reserved it to you as an exercise.

note

Java mainly assigns names to threads running the main () method, start thread. You particularly look at the default exceptions of the JVM of the thread "Main" to process print messages when the start thread is thrown out of an exception.

Sleep or stop sleep

Behind this column, I will introduce you to you - repeat the graphics on a surface, which is slightly different from the completion of a sports screen. To complete the animation, a thread must be suspended when it displays two consecutive pictures. Call Thread's Static Sleep (Long Millis) method forces a thread to stop Millis milliseconds. Another thread may interrupt the hibernated thread. If this happens, the hibernated thread will wake up and throw an InterruptedException object from the Sleep (long Millis) method. As a result, the code that calls SLEEP (long Millis) must be in a try code block - or the code method must include InterruptedException in its own Throws clause.

To demonstrate Sleep (Long Millis), I wrote a Calcpi1 application. This application starts a new thread to make the value of the mathematical constant Pi with a mathematical algorithm. When the new thread is calculated, the start thread is started to abort 10 milliseconds by calling Sleep (long Millis). After starting the line, it will print the value of the PI, where the new thread is stored in the variable PI. Table 3 gives the source code of Calcpi1: Table 3. Calcpi1.java

// Calcpi1.java

Class Calcpi1

{

Public static void main (string [] args)

{

Mythread MT = new mythread ();

Mt.start ();

Try

{

Thread.sleep (10); // Sleep 10 ms

}

Catch (InterruptedException E)

{

}

System.out.println ("pi =" mt.pi);

}

}

Class mythread extends thread

{

Boolean negative = true;

Double Pi; // The default is initialized to 0.0

Public void Run ()

{

For (int I = 3; i <100000; i = 2)

{

IF (Negative)

PI - = (1.0 / i);

Else

Pi = (1.0 / i);

NEGATIVE =!

}

Pi = 1.0;

PI * = 4.0;

System.out.println ("Finished Calculating Pi");

}

}

If you run this program, you will see the output as follows (but may also be different):

Pi = -0.2146197014017295

Complete calculation PI

Why is the output incorrect? After all, the value of the PI should be approximately equal to 3.14159. The answer is: Start the thread awake too fast. When the new thread is just starting to calculate the PI, the start thread wakes up to read the current value of the PI and print it. We can compensate by adding 10 millisecond delays to a longer value. This longer value (unfortunately it relies on the platform) will give the new thread a chance to complete the calculation before starting the line. (Later, you will learn a technology that does not rely on the platform, it will prevent the startline from being built until the new thread is completed.)

note

Threads simultaneously provide a Sleep (Long Millis, int NANOS) method, which will thread Millis milliseconds and Nanos nanoseconds. Because most JVM-based platforms do not support the decomposition of nanoseconds, the JVM thread processing code enters the nanosecond number to the approximate value of millisecond numbers. If a platform does not support millisecondary decomposition, JVM thread processing code will be approximately multiple of the minimum level of milliseconds to support the minimum level of the platform.

Is it dead or live?

When a program is called the Start () method, there is a period of time (for initialization) before a new thread calls RUN (). After run () returns, there is a period of time before the JVM clear thread. JVM believes that the thread immediately activates a thread call Run (), and after the thread executes Run () and Run () returns. During this time interval, thread's isalive () method returns a Boolean true value. Otherwise, the method returns a false value.

Isalive () is helpful in a thread that needs to wait for another thread to complete its Run () method before the first thread can check the results of other threads. In essence, those threads need to wait for a while loop. When IsAlive () returns true value for other threads, the Waiting thread calls Sleep (Long Millis, Int Nanos) periodically (avoiding more CPU loops). Once isalive () returns a false value, wait for the thread to check the results of other threads. Where will you use this technology? For the starter, a modified version of a Calcpi1, where is the thread waiting for the new thread to be completed before the value of the PI is printed? Table 4's Calcpi2 source code demonstrates this technology:

Table 4. Calcpi2.java

// Calcpi2.java

Class Calcpi2

{

Public static void main (string [] args)

{

Mythread MT = new mythread ();

Mt.start ();

While (mt.isalive ())

Try

{

Thread.sleep (10); // Sleep 10 ms

}

Catch (InterruptedException E)

{

}

System.out.println ("pi =" mt.pi);

}

}

Class mythread extends thread

{

Boolean negative = true;

Double Pi; // Default initialization into 0.0

Public void Run ()

{

For (int I = 3; i <100000; i = 2)

{

IF (Negative)

PI - = (1.0 / i);

Else

Pi = (1.0 / i);

NEGATIVE =!

}

Pi = 1.0;

PI * = 4.0;

System.out.println ("Finished Calculating Pi");

}

}

The start thread of Calcpi2 is hibernated in 10 milliseconds until mt.isalive () returns a false value. When those occurring, the start thread exits and prints the contents of PI from its While loop. If you run this program, you will see the output (but not necessarily the same):

Complete calculation PI

Pi = 3.1415726535897894

This is not, now it looks more accurate?

note

A thread may call it itself by the isalive () method. However, this is meaningless because isalive () will return true value.

Fitness

Because the While loop / isalive () method / sleep () method technology proves is useful, Sun is packaged in a combination of three methods: join (), Join (long Millis) and Join (Long Millis, Int Nanos) ). When the current thread wants to wait for the end of the other thread, call JOIN (). Conversely, when it wants to wait for any thread to wait for other threads to end or wait until Millis milliseconds and Nanos nanosecond combinations, the current thread calls Join (Long Millis) or JOIN (Long Millis, Int Nanos). (As a Sleep () method, the JVM thread processing code will give the parameter value of Join (long Millis) and Join (INT NANOS).) Table 5's Calcpi3 source code demonstrates a call to join ():

Table 5. Calcpi3.java

// Calcpi3.java

Class Calcpi3

{

Public static void main (string [] args)

{

Mythread MT = new mythread ();

Mt.start ();

Try

{

Mt.join ();

}

Catch (InterruptedException E)

{

}

System.out.println ("pi =" mt.pi);

}

}

Class mythread extends thread

{

Boolean negative = true;

Double Pi; // Default initialization into 0.0

Public void Run ()

{

For (int I = 3; i <100000; i = 2)

{

IF (Negative)

Pi - = (1.0 / i);

Else

Pi = (1.0 / i);

NEGATIVE =!

}

Pi = 1.0;

PI * = 4.0;

System.out.println ("Finished Calculating Pi");

}

}

The start thread of Calcpi3 is waiting to end with the Mythread object to end the thread referenced by the MT. Then start the value of the thread print PI, which is the same as the output of CALCPI2.

caveat

Don't try to connect the current thread with your own, because it will wait forever.

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

New Post(0)