In the computer field, we say concurrency (Concurrency) refers to the simultaneous operation of a series of tasks. If a computer has more than one processor or a multi-core processor, this concurrency (simultaneity) is really meaningful, but if a computer has only one single-core processor, this concurrency is not really concurrent
One, the creation and operation of threads
Inherit the Thread class and override the Run () method
Create a class for the Runnable interface. Use the thread constructor with parameters to create the thread object . This parameter is an object of the class that implements the Runnable interface
Example implementations:
package org.test.concurrency;/** * @author kucs * * Create a class that implements the Runnable interface. Use the thread constructor with parameters to create objects * This parameter is an object of the class that implements the Runnable interface * */public class calculator implements runnable { private int number; public Calculator (int number) { this.number = number; } @Override Public void run () { // TODO Auto-generated method stub for (int i = 0;i < 10;i++) { system.out.printf ("%s: %d * %d = %d\n ", thread.currentthread (). GetName (), number,i,i*number); } }}package org.test.concurrency;public class main { public static void main (String[] args) { /* Create a loop that executes 10 times * Each cycle creates a calculator object and a thread object *&nThis thread object uses the Calculator object you just created as the constructor's argument * then calls the start () method of the thread object you just created * / for (int i = 0;i < 10;i++) { calculator Calculator = new calculator (i); thread thread = new thread (calculator); thread.start (); } }}
Run results
650) this.width=650; "title=" run result. png "alt=" wkiom1doki7bkgybaabacqylez4036.png-wh_50 "src=" http://s1.51cto.com/ Wyfs02/m00/82/37/wkiom1doki7bkgybaabacqylez4036.png-wh_500x0-wm_3-wmp_4-s_775859096.png "/>
When the start () method of the thread object is called, another thread of execution is created.
If a thread calls the System.exit () directive to end the execution of the program, all threads will end
For a class that implements the Runable interface, creating a thread object does not create a new execution thread, and similarly, calling its run () method does not create a new thread. only the start () method that calls it will create a new thread of execution.
Second, the acquisition and setting of thread information
The thread class has some properties for saving information. These properties can be used to identify the state of a thread or to control the priority of a thread.
ID: A thread-unique identifier was saved
Name: The thread name is saved
Priority: The precedence of the thread object is saved. The thread's priority is incremented from 1 to 10. Changing thread priority is not recommended
Status: The state of the thread is saved. In Java, threads have a status of 6: New,runnable,blocked,waiting,time waiting or terminated
JDK6 version of the thread part of the source code
public class thread implements runnable { /* make sure registernatives is the first thing <clinit> does. */ private static native void registernatives (); static { registernatives (); } private char name[]; private int priority; private Thread threadQ; private long eetop; /* whether or not to single_step this thread. */ private boolean single_step; /* Whether or not the thread is a daemon thread. */ private boolean daemon = false; /* jvm state * / private boolean stillborn = false; /* What will be run. */ private Runnable target; /* the group of this thread */ private ThreadGroup group; /* The context ClassLoader for this thread */ private classloader contextclassloader; /* The inherited AccessControlContext of this thread */ private AccessControlContext inheritedAccessControlContext; /* For autonumbering anonymous threads. */ private Static int threAdinitnumber; private static synchronized int nextthreadnum () { return threadinitnumber++; } /* threadlocal values pertaining to this thread. This map is maintained * by the ThreadLocal class. */ threadlocal.threadlocalmap threadlocals = null; private long Stacksize; /* * jvm-private state that persists after native thread termination. */ private long nativeParkEventPointer; /* * thread id */ private long tid;
We are transforming the main class with the following code
package org.test.concurrency;import java.io.file;import java.io.filewriter;import java.io.ioexception;import java.io.printwriter;import java.lang.thread.state;public class Main { public static void main (String[] args) { /* * create a thread array with a capacity of 10 to store threads Create a thread.state array with a capacity of 10 to store thread state */ Thread[] threads = new thread[10]; thread.state[] states = new Thread.State[10]; /* * Create an array of Calculator objects with a capacity of 10, set different numbers for each object * then use them as parameters to the thread constructor to create 10 thread objects. Set 5 thread priority to highest, 5 for lowest */ for (int i = 0; i < 10; 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); } /* * Create a PrintWriter object that writes the state of the thread to the file */ try { file file = new file ("D:\\thread_log.txt") ; if (!file.exists ()) { file.createnewfile (); } filewriter fw = new filewriter (file); &NBSP;&NBSP;&NBSP;PRINTWRITER&NBSP;PW = new printwriter (FW); for (int i = 0; i < 10; i++) {// system.out.println ("main : status of thread " + i + ": " + threads[i].getstate ()); Pw.println ("Main : status of thread " + i + ": " + threads[i].getstate ()); states[i] = threads[i].getstate (); } /* starts execution of 10 threads */ for (int i = 0; i < 10; i++) { threads[i].start (); } boolean finish = False; while (!finish) { for (int i = 0;i<10;i++) { if (Threads[i].getstate () != states[i]) { writethreadinfo (Pw,threads[i],states[i]); } } } finish = true; for (int i = 0;i<10; i++) { finish = finish && (threads[i].getState () == state.terminated), &Nbsp; } pw.close (); } catch (IOException e) { // todo auto-generated catch block e.printstacktrace (); } } private static void writethreadinfo (PrintWriter pw, Thread thread, state state) { // todo auto-generated method stub 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 : ", " ***************************\n "); }}
Run results
Main : status of thread 0:newmain : status of thread 1: Newmain : status of thread 2:newmain : status of thread 3: Newmain : status of thread 4:newmain : status of thread 5: Newmain : status of thread 6:newmain : status of thread 7: Newmain : status of thread 8:newmain : status of thread 9: Newmain : id 9 - thread 0main : priority: 10main : old state: newmain :main : id 10 - thread 1main : priority : 1main : old state: newmain :main : id 11 - thread 2Main : Priority: 10Main : old State: NEWMain :Main : Id 12 - thread 3main : priority: 1main : old state: newmain :main : id 13 - thread 4main : priority: 10main : old state: newmain :main : id 14 - thread 5main : priority: 1main : old state: newmain :main : id 15 - thread 6
Third, the interrupt of the thread
Java provides a thread break mechanism that we can use to end a thread. This mechanism requires checking if it is interrupted, and then deciding whether to respond to the interrupt request. The thread ignores the interrupt request and continues execution. We use the isinterrupted () method to check if the thread is interrupted. If the isinterrupted () return value is true, it indicates that the thread has been interrupted. We use thread. interrupt () to break the thread.
Iv. Thread hibernation and recovery
The Sleep () method of the thread is used to hit the state where the thread sleeps. Thread hibernation does not occupy any resources of the computer. The sleep () method takes an integer value as a parameter, indicating the number of milliseconds the thread suspends execution .
Another way to use the sleep () method is to invoke it through the Timeunit enumeration class element. This method also uses the sleep () method of the thread class to hibernate the current thread.
Five, waiting for the termination of the thread
In some cases we have to wait for the thread to terminate. To achieve this, we use the thread's join () method. When a thread object's join () method is called, the thread that invokes it is suspended until the thread object finishes its task.
Vi. Daemon Threads
There is a special thread called the Daemon Thread (Daemon) in Java. This thread has a low priority, and typically, when no other thread in the same application is running, the guard line friend run. When the daemon thread is the only program running in the program, the JVM ends the program when the daemon executes.
Typically, a daemon thread is an infinite loop to wait for a service request or to perform a thread's task. They cannot do important work because it is impossible to know when the daemon will be able to get the CPU time slice, and when no other thread is running, the daemon thread may end at any time. A typical daemon thread is the Java garbage collector (garbage Collector).
Vii. Grouping of threads
Java provides a Threadgroup class that represents a set of threads. A thread group can contain thread objects and can include other thread group objects, which are a tree structure. For similar content, see Java Multithreading basics
This article is from the "Ah Cool blog source" blog, please make sure to keep this source http://aku28907.blog.51cto.com/5668513/1788953
Java concurrency (i) thread management