1, using the Inheritance thread class creation thread
to define a subclass of a Java.lang.Thread class and override its Run method:
Class Mythread extends thread{
public void Run () {...}
}
and then generates the object for the class: Mythread mythread = new Mythread (...);
2, creating a thread by implementing the Runnable interface
defines the thread class that implements the Runnable interface
Class Mythread implements runnable{
public void Run () {...}
}
and then construct the thread class using the thread class:
thread mythread = new Thread (target); There is only one method in the
runnable: public void Run ();
Thread Start: Mythread.start (); 3, method of constructing thread class:
Thread ()
Thread (Runnable target)
Thread (Runnable target, string name)
Thread (string name)
Thread (threadgroup Group, Runnable target)
Thr EAD (threadgroup group, Runnable Target, string name)
Thread (threadgroup Group, string name)
group-indicates the thread group to which the thread belongs;
Target-The object that provides the thread body, you must implement the Runnable interface's run () method,
name-the thread name, each thread has its own name, and if not specified, Java automatically assigns a unique name to the thread;
Comparison of two ways:
Use the Runnable interface
to separate the CPU, code, and data to form a clear model; The
can also inherit from other classes;
Keep the program style consistent;
You can use static methods such as Thread.CurrentThread () to get the current thread to control in classes that implement the Runnable interface;
directly inherit the thread class
can no longer inherit from other classes;
Writing is simple, you can manipulate threads directly; 4, thread priority
The priority of the thread is represented by a number, ranging from 1 to 10, and the larger the number, the higher a thread's default priority is 5;
static member variables defined in the thread class:
Thread.min_ PRIORITY = 1
thread.max_priority = ten
Thread.norm_priority = 5
The new thread inherits the priority of its parent thread. In general, the main thread (main) has a normal priority;
the method to get and set the priority of the thread object:
int getpriority ();
void setpriority (int newpriority);
5, thread State and control
Create state
New operator create thread object;
Ready state
The call thread's start () method starts the thread so that the thread is ready, and the thread may not be actually executing;
Run Status:
The JVM's thread dispatch manager selects the thread that is in the ready state, make it occupy the code in the start run () method of the CPU until it is terminated or blocked;
Blocking state: The thread for this state is not running until the blocking reason is removed, the thread is in a ready state, and the thread queue is entered again. Run again from the end;
calls the sleep () method; The
Suspend () method is invoked;
The thread invokes the Wait () method for waiting for a condition variable;
Thread blocking occurs in the input/output stream;
A method that causes a thread to return to a ready state for each of the above four scenarios:
The parameters in the sleep () method are rest time, in milliseconds, and when the time passes, the thread is ready.
Once a thread calls the Suspend () method, only other threads can invoke its resume () method recovery.
If a thread waits for a condition variable, if you want to stop waiting, you need the object that contains the condition variable to invoke the Notify () or the Notifyall () method.
A specific I/O instruction ends the blocking state.
Termination status: There are two conditions that can cause the thread to terminate
Natural undo, the normal running thread completes all its work;
Call the Stop () method to force termination;
Thread provides a method IsAlive () that returns true if the thread has started, but not terminated, and returns false, indicating that the thread was not started or terminated.
If the IsAlive () method returns True, it cannot distinguish between a ready state, a blocking state, or a running state.
Precautions:
For any state, if the invoked method and state do not match, it can cause illegal state handling exceptions. Like what. When a line isconcurrently is created, only the start () or stop () method can be invoked, which can cause illegal state processing if other methods are invoked.
Sleep method
You can invoke the static method of thread:
public static void sleep (Long mills) throws Interruptedexception
Example: Testinterrupt.java
Join method
Merging a thread is a relatively primitive form of communication between threads;
For example: In ThreadX, execute the following code:
try{thready.join ();} catch (Interruptedexception e) {...}
THREADX will be blocked, waiting for the death of Thready;
Example: Testjoin.java
Yield method: The initiative to give up the CPU, to the same level or more advanced thread execution opportunities;
Yield () cannot be abused, and context switching between threads can result in excessive overhead and may not exceed 5 times in 1 seconds;
Example: Testyield.java
Daemon thread (daemon thread)
Has the lowest priority for providing services to other objects and threads in the system in the background; it should be a separate thread, and its run () method is an infinite loop.
The way to set a user thread as a daemon is to invoke the Setdaemon (Boolean on) method of the threading object before the thread object starts.
You can use the Isdaemon () method to determine whether a thread is a daemon;
The difference between a daemon and another thread is that if the daemon is the only running thread, the program automatically exits
A typical example of a daemon is a system resource recycling thread in the JVM, which is always running in a low-level state for real-time monitoring and management of recyclable resources in the system. 6, Java's thread synchronization mechanism:
Thread mutex lock for shared data
Only one thread is allowed to operate on a shared data object at any time
Thread synchronization mechanism for transferring data
For the need to transfer the data of the multiple threads must be synchronized, in unison, to ensure timely and accurate transmission of data received;
Each object corresponds to a token that can be called a "mutex", which guarantees that only one thread can access the object at any one time;
The keyword synchronized is used to represent mutexes. When an object is decorated by synchronized, it indicates that the object can only be accessed by one thread at any one time;
Ways to implement synchronization examples did not do
More precise control of thread synchronization through thread monitor using a shared condition variable
Using Wait (), notify (), Notifyall () method, to ensure the synchronization between producers and consumers: production of one, consumption one;
Summary of multithread synchronization mechanism:
For objects or methods shared by multiple threads, use synchronized modification;
If a thread has to wait for the state of an object to change, it is implemented by entering the synchronization method or by invoking the waiting () method;
Whenever a method modifies the state of a shared object, it should call Nofity () or notifyall () for notification;
Deadlock problem
A thread can be blocked, and a so-called deadlock (deadlock) is formed when the resource needed to support its operation is locked by another blocking thread;
The Java language itself does not provide a mechanism to prevent deadlocks
Deadlock may lurk in the running program, preventing deadlock is an important task in the design phase.
Philosophers eating problems; deadlock Example: Testdeadlock.java
method to solve deadlock problem: to impose a sort of conditional variable;
1. The communication between threads can flow by pipeline.
To create a pipe flow:
PipedInputStream pis = new PipedInputStream ();
PipedOutputStream pos = new PipedOutputStream (PiS);
Or:
PipedOutputStream pos = new PipedOutputStream ();
PipedInputStream pis = new PipedInputStream (POS);
1. Use the filter flow to pack the pipeline flow to read and write
PrintStream p = new PrintStream (POS);
P.println ("Hello");
DataInputStream d = new DataInputStream (PiS);
D.readline ();
2. Passing information through an intermediate class.
A pipe stream can connect two threads of communication between
In the following example, there are two threads running, one to output information, and one to read information.
The output of a write thread is defined as the input of a read thread through a pipe stream.
OutStream = new PipedOutputStream ();
instream = new PipedInputStream (OutStream);
New Writer (OutStream). Start ();
New Reader (instream). Start ();