Thread threads simple to use

Source: Internet
Author: User

This is a summary of what you did when you were learning about threads


One: Create a thread
Inherit the thread class
The thread class (thread) contains a procedure (method) that can be run: the Run () method
2) The steps to create a specific thread are as follows:
First, inherit the Thread class
Second, rewrite the Run method (that is, update the running process) to implement the user's own process
Third, create a thread instance (that is, create a thread)
Finally, start the thread with the start () method of the thread instance, and the thread will execute run () as soon as possible after starting 0.

5 State of the thread
1) New State
When the program creates a thread with the new keyword, the thread is in the new state, and the thread is not started.
When the thread object calls the start () method, the thread starts and enters the Runnable state
2) Runnable Operational (Ready) status
When the thread is in the Runnable state, it indicates that the thread is ready to wait for the CPU
3) Running running (running) status
If the thread acquires the CPU, it enters the Running state and begins the execution of the thread body, the inside of the Run () method
Capacity
Attention:
If the system just has 1 CPUs, then at any point in time just have 1 threads in Running State;
If it is a dual-core system, then there will be 2 threads in the Running state at the same point in time.
However, when the number of threads is greater than the number of processors, multiple threads will still be rotated on the same CPU
When a thread starts running, it is not likely to remain in the Running state if it is not completed in a flash.
Threads are interrupted during execution, in order to allow other threads to get the chance to execute, such as a thread scheduling policy
Slightly depends on the underlying platform. For a preemptive strategy platform, the system will give each executable thread a small
Period of time to process anything, when the time period (time slice) is exhausted, the system will deprive the thread of the resources (CPU),
Let other threads get the chance to run.
Call the yield () method to enable the thread to enter the Runnable state by the Running state
4) block blocking (pending) status
When the following conditions occur, the thread goes into a blocking state:
The thread calls the sleep () method to voluntarily discard the occupied CPU resources
The thread calls a blocking IO method (such as a console input method), and before the method returns, the line
Process is blocked

When the executing thread is blocked, the other thread gets the execution opportunity. It is important to note that when blocking ends
, the thread enters the Runnable state instead of directly into the Running state
5) Dead Death status
When the thread's run () method finishes executing, the thread enters the Dead state
It is important to note that you should not attempt to invoke the start () method on a dead thread, and that the thread will not be able to die again as
Thread execution, the system throws a Illegalthreadstateexception exception






Note----


1) When the new operation creates a thread, the thread enters the new state (initial state)
2) After invoking the start () method, the thread enters the Runnable state (ready state) from the New state
The start () method is called in the Main () method (Running state).
3) After the thread ends, enter the Dead state (dead state) and be garbage collected by the object
4) after the main () method ends, other threads, such as P1 and P2 in the previous example, start rushing into the Running state
By who is the bottom operating system decision (operating system allocation time slice)
Single-core processor: At a point in time just has a thread in the Running State; dual-core Processor: 2
If P1 enters the Running state, P1 enters Runnable when the time slice that the operating system assigns to it expires.
Status, P2 into Running state
During the period when it is possible for other threads of the process to obtain the time slices, then P1 and P2 simultaneously enter the Runnable state,
Wait for the operating system to allocate time slices
5) After the thread enters the Dead state, just can be garbage collected, can not start again
6) If the thread is calling the yield () method while it is running, the active state enters the Runnable form by Running
State


State management
1) Let the CPU Thread.yield ()
The current thread yields the processor (leaving the Running state), causing the current thread to enter the Runnable state wait
2) Sleep thread.sleep (Times)
Causes the current thread to discard the processor from Running into the Block state, hibernate times milliseconds, and then back to Runnable
Interruptedexception occurs if another thread interrupts the Block (sleep) of the current thread.








1) Priority of threads (when resources are tight, prioritize as much as possible)
T3.setpriority (thread.max_priority); Set to the highest priority------------the highest level is 10, the lowest level is 1, and the default level is 5
By default there are 10 priorities, and higher-priority threads have more chances to execute (enter the Running state). Chance of
How much not to intervene through code
The default priority is 5
2) Background thread (daemon thread, Sprite thread)-----------------------demo (background thread set to loop 100 times output, foreground loop 10 output)
T1.setdaemon (TRUE);
End of Java process: The end of all foreground threads at the end of the Java process
At the end of the current thread, the end of the background thread will be stopped!
3) Get the thread name
GetName ()
4) Get current thread
Thread main = Thread.CurrentThread ();






Implement thread the second way (because Java single inheritance)
Implementing the Runnable Interface
Implementation steps:
Implement the Runnable interface, implement the Run () method, provide and dispatch the process
Create an instance of this class, use this instance as the thread constructor parameter, create the thread class
Start a thread using the start () method


Demonstrate
You can also use anonymous inner classes


Thread T1=new thread () {


@Override
public void Run () {
SYSTEM.OUT.PRINTLN ("Thread 1 start");
}
};
T1.start ();
Runnable r=new Runnable () {

@Override
public void Run () {
SYSTEM.OUT.PRINTLN ("Thread 2 start");
}
};
Thread t2=new thread (r);
T2.start ();
Thread T3=new Thread (new Runnable () {

@Override
public void Run () {
System.out.println ("Thread 3 start");
}
});
T3.start ();
New Thread () {
@Override
public void Run () {
System.out.println ("Thread 4 start");
}
}.start ();
New Thread (New Runnable () {

@Override
public void Run () {
TODO auto-generated Method Stub

}
}). Start ();








Io B lock is triggered by IO operation, same as sleep block, and sleep block is triggered by the sleep () method
 Trigger methods such as ReadLine (), nextline (), Next (), Nextint (), etc.
 General Io Read method will occur IO Block






1) asynchronous
concurrency, each doing their own. such as: A group of people on the truck
2) Sync
Unison of the process. such as: A group of people lined up on the bus






1) A "Thread concurrency security issue" occurs when multiple threads concurrently read and write to the same critical resource, if the multi-threaded synchronous
Ask critical resources, you can solve them.
2) Common critical resources:
 Multi-threaded shared instance variables
 Static public variables
3) Use synchronous code blocks to resolve thread concurrency security issues
synchronized (Sync monitor) {
}
 The synchronization monitor is an arbitrary object instance.  is a mutually exclusive locking mechanism between multiple threads. Multiple threads to make
Synchronizing mutexes with the same monitor object



Synchronized (this) {
}
If the whole process of a method needs to be synchronized, you can simply use the synchronized adornment method, which is equivalent to the entire method
The synchronized (this)
Minimize sync range and increase concurrency efficiency






int count=20;
@Override
public void Run () {
for (int i=0;i<50;i++) {
if (count>0) {
try {
Thread.Sleep (1000);
} catch (Interruptedexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
System.out.println (Thread.CurrentThread (). GetName () + "number window sell" +count--+ "ticket");
}
}
}




Main


Ticketsouce t=new ticketsouce ();
New Thread (T, "T1"). Start ();
New Thread (T, "T2"). Start ();
New Thread (T, "T3"). Start ();




Synchronized this keyword has two uses 1, the method name before the formation of synchronization method, 2, placed in front of the block to form a synchronization block.
(1) Synchronization method
Public synchronized void Sale () {
System.out.println (Thread.CurrentThread (). GetName () + "number window sell" +count--+ "ticket");
}
-----Run


Synchronized (this) {
if (count>0) {
try {
Thread.Sleep (1000);
} catch (Interruptedexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
System.out.println (Thread.CurrentThread (). GetName () + "number window sell" +count--+ "ticket");
}
}








Thread threads simple to use

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.