Java Concurrency Programming Example (ii): Getting and setting thread information _java

Source: Internet
Author: User
Tags arrays thread class

The thread class contains several properties that represent information that helps us identify threads, observe their status, control their precedence, and so on. These threads include several of the following:

ID: This attribute represents the unique identity of each thread;
Name: This property stores the name of each thread;
Priority: This property stores the priority of each thread object. Thread precedence is divided between 1 and 100 levels, 1 is the lowest priority, and 10 is the highest priority. It is not recommended to modify the priority of a thread, but if there is a need to do so, you can try it.
Status: This property stores the state of the thread. There are six different states of a thread: new, Running (runnable), blocking (blocked), Waiting (waiting), timed waiting (time waiting), or terminating (terminated). The state of a thread must be one of them.

In this section, we will develop a program that creates 10 new threads in the program and sets the name and priority of each thread. It then executes the thread and observes the state information of the thread until the thread execution ends. Again, these threads still compute a multiplication table for a number.

Know it

Follow the steps shown below to implement the example:

1. Create a class named Calculator that implements the Runnable interface. The code is as follows:

Copy Code code as follows:

public class Calculator implements Runnable {

2. Declares a private reshaping property, named number, that implements the constructor of the class to initialize the property just declared. The code is as follows:

Copy Code code as follows:

private int number;

public Calculator (int number) {
This.number = number;
}

3. Implement the Run () method, which is the program that runs when the thread we create executes (instruction), so the method is used to compute the multiplication table. The specific code is as follows:

Copy Code code as follows:

@Override
public void Run () {
for (int i = 0; i < i++) {
System.out.printf ("%s:%d *%d =%d\n",
Thread.CurrentThread (). GetName (),
Number, I, I * number);
}
}

4. Now, let's implement the main class of the example application (main). Create a class named Main that adds the main method to the class. The code is as follows:
Copy Code code as follows:

public class Main {
public static void Main (string[] args) {

5. Create two arrays containing 10 elements, one thread type, one thread.state type, and then all initialized. These two arrays, one to store the threads we will execute, and another to store the state of those threads. The code is as follows:

Copy Code code as follows:

thread[] threads = new THREAD[10];
thread.state[] status = new Thread.state[threads.length];

6. Create 10 Calculator objects, and use different numbers to initialize each object. Use these calculator objects to create 10 thread objects and store them in the creation array above. At the same time, set the priority of these threads, five to the highest priority, and five to the lowest priority level. The code is as follows:

Copy Code code as follows:

for (int i = 0; i < threads.length; i++) {
Threads[i] = new Thread (new Calculator (i));
if ((i% 2) = = 0) {
Threads[i].setpriority (thread.max_priority);
} else {
Threads[i].setpriority (thread.min_priority);
}
Threads[i].setname ("thread-" + i);
}

7. Create a PrintWriter object that records the transformation of thread state to a file. The code is as follows:
Copy Code code as follows:

Try (FileWriter file = new FileWriter ("D:\\thread.log");
PrintWriter pw = new PrintWriter (file)) {

JAVA7 syntax is used here, so please upgrade the JDK to version seventh and set the compilation tool to Java7. Otherwise you will report a grammatical error.

8. Write the status of all threads to a file. Now, the state should be new. The code is as follows:

Copy Code code as follows:

for (int i = 0; i < threads.length; i++) {
Thread thread = Threads[i];
Pw.println ("Main:status of Thread" + i +
":" + threads[i].getstate ());
Status[i] = Threads[i].getstate ();
}

9. Start all threads. Code in:
Copy Code code as follows:

for (int i = 0; i < threads.length; i++) {
Threads[i].start ();
}

10. On the other hand, we monitor the thread until the end of the thread execution. If we detect a change in the state of the thread, the thread state is immediately written to the file. The code is as follows:
Copy code code as follows:

Boolean finish = false;

while (!finish) {
for (int i = 0; i < threads.length; i++) {
if (Threads[i].getstate ()!= status[i]) {
Writethreadinfo (PW, threads[i], status[i]);
Status[i] = Threads[i].getstate ();
}
}
finish = true;
for (int i = 0; i < threads.length; i++) {
finish = Finish
&& (threads[i].getstate () = = Thread.State.TERMINATED);
}
}

11. Implement the Writethreadinfo method, which writes the thread ID, name, priority, Old state, and new state to the file. The code is as follows:

Copy Code code as follows:

/**
* Output the state of a thread to a file.
*
* @param pw PrintWriter Objects
* @param thread object that requires output status for thread
* @param the Old State thread
*/
private static void Writethreadinfo (PrintWriter pw,
Thread thread, thread.state state) {
pw.printf ("Main:id%d =%s\n", Thread.getid (), Thread.getname ());
pw.printf ("Main:priority:%d\n", thread.getpriority ());
pw.printf ("Main:old State:%s\n", state);
pw.printf ("Main:new State:%s\n", thread.getstate ());
pw.printf ("Main: ********************************\n");
}

12. Run the example, and then open the Thread.log file to see the evolution of all threads.

Know the reason why

The following is a fragment of the contents of the Thread.log file. As can be seen from the contents of the file, high priority threads are roughly executed earlier than low-priority threads. In addition, you can see the state evolution process for each thread.

Copy Code code as follows:

Main: ********************************
Main:id = Thread-2
Main:priority:10
Main:old state:blocked
Main:new state:terminated
Main: ********************************
Main:id = Thread-4
Main:priority:10
Main:old state:blocked
Main:new state:terminated
Main: ********************************
Main:id = Thread-5
Main:priority:1
Main:old state:blocked
Main:new state:terminated
Main: ********************************

The following is the output fragment of the console. The output is the multiplication table computed by each thread, along with all the thread calculation processes. At the same time, the evolutionary process of each thread can be seen more fine-grained from here.

Copy Code code as follows:

THREAD-8:8 * 2 = 16
THREAD-8:8 * 3 = 24
THREAD-8:8 * 4 = 32
THREAD-6:6 * 0 = 0
THREAD-6:6 * 1 = 6
THREAD-6:6 * 2 = 12
THREAD-6:6 * 3 = 18
THREAD-6:6 * 4 = 24
THREAD-6:6 * 5 = 30
THREAD-6:6 * 6 = 36
THREAD-6:6 * 7 = 42
THREAD-6:6 * 8 = 48
THREAD-6:6 * 9 = 54
THREAD-5:5 * 0 = 0
THREAD-5:5 * 1 = 5
THREAD-5:5 * 2 = 10
THREAD-5:5 * 3 = 15
THREAD-5:5 * 4 = 20

The thread class has all the attributes that are required to store thread information. Java Virtual machines use thread precedence to schedule a thread to use the CPU at every moment, and to set the state of each thread based on the situation of the thread.

If you do not set the name of the thread, the Java virtual Opportunity uses this format to assign a name, THREAD-XX, where XX is a number. We cannot modify the ID of the thread and the state of the thread. The thread class also does not implement the SetID () and SetStatus () methods to allow these modifications to be made.

Endless

In this section, we learned how to use the thread object to access threading information. In fact, the Runnable implementation class also runs our access to this information. The static method CurrentThread () of the thread class can obtain the object of the executing Runnable implementation class, thereby accessing the thread's information.

Note that if you try to set a priority other than 1 to 10, setpriority () throws an exception named IllegalArgumentException.

Copycat

This article is from the "Java 7 Concurrency Cookbook" (D-Gua to "Java7 concurrent Sample Set") translation, only as learning materials used. No authorization shall be applied to any commercial act.

Small has become

Complete code for the calculator class

Copy Code code as follows:

Package com.diguage.books.concurrencycookbook.chapter1.recipe2;

/**
* DATE:2013-09-13
* time:19:49
*/
public class Calculator implements Runnable {
private int number;

public Calculator (int number) {
This.number = number;
}

@Override
public void Run () {
for (int i = 0; i < i++) {
System.out.printf ("%s:%d *%d =%d\n",
Thread.CurrentThread (). GetName (),
Number, I, I * number);
}
}
}

The complete code for the main class

Copy Code code as follows:

Package com.diguage.books.concurrencycookbook.chapter1.recipe2;

Import Java.io.FileWriter;
Import java.io.IOException;
Import Java.io.PrintWriter;

/**
* DATE:2013-09-13
* time:19:51
*/
public class Main {
public static void Main (string[] args) {
thread[] threads = new THREAD[10];
thread.state[] status = new Thread.state[threads.length];

        for (int i = 0; i < threads.length i++) {
    & nbsp;       Threads[i] = new Thread (new Calculator (i));
            if ((i% 2) = = 0) {
                 threads[i].setpriority (thread.max_ PRIORITY);
           } else {
                 threads[i].setpriority (thread.min_priority);
           }
            threads[i].setname ("thread-" + i);
       }

        Try (FileWriter file = new FileWriter ("D:\\thread.log");
              PrintWriter pw = new PrintWriter (file) {
            for (int i = 0; i < threads.length i++) {
&nbs p;               thread thread = threads[i];
                pw.println ("Main : Status of Thread + i +
                         ":" + threads[i].getstate ());
                Status[i] = Threads[i].getstate ();
           }

for (int i = 0; i < threads.length; i++) {
Threads[i].start ();
}

Boolean finish = false;

while (!finish) {
for (int i = 0; i < threads.length; i++) {
if (Threads[i].getstate ()!= status[i]) {
Writethreadinfo (PW, threads[i], status[i]);
Status[i] = Threads[i].getstate ();
}
}
finish = true;
for (int i = 0; i < threads.length; i++) {
finish = Finish
&& (threads[i].getstate () = = Thread.State.TERMINATED);
}
}

catch (IOException e) {
E.printstacktrace ();
}
}

/**
* Output the state of a thread to a file.
*
* @param pw PrintWriter Objects
* @param thread object that requires output status for thread
* @param the Old State thread
*/
private static void Writethreadinfo (PrintWriter pw,
Thread thread, thread.state state) {
pw.printf ("Main:id%d =%s\n",
Thread.getid (), Thread.getname ());
pw.printf ("Main:priority:%d\n", thread.getpriority ());
pw.printf ("Main:old State:%s\n", state);
pw.printf ("Main:new State:%s\n", thread.getstate ());
pw.printf ("Main: ********************************\n");
}
}

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.