J2SE Summary (2) -- thread, j2se summary thread
1. Highlights of this Chapter
Thread concept: different execution paths and program branches contained in a program at the same time
Create and start
Scheduling, priority
Status Control
Synchronous and asynchronous
2. Differences between processes and threads
Process: static, exe, class, dos only support single process
Essence: thread execution
3. Create and start
1) Implement the runnable interface
Thread myThread = newThread (target) // difference from the second method
Runnable has only one run () method to define the method to be executed by a specific thread.
Thread static call
Start (): Start the thread
Instance:
Class Runner1 implements Runnable {
Public void run (){
For (int I = 0; I <100; I ++ ){
System. out. println ("Runner1:" + I );
}
}
}
Public class TestThread1 {
Public static void main (string args []) {
Runner1 r = new Runner1 (); // 1.1
// R. run (); // method call instead of starting a new thread
Thread t = new thread // 1.2
T. start (); // start
For (int I = 0; I <100; I ++ ){
System. out. println ("main thread .... "+ I );
}
}
}
2) directly inherited from thread
Public Runner1 extends Thread {
Public void run (){
For (int I = 0; I <100; I ++)
{
System. out. prinln ("Runner1:" + I );
}
}
}
Because it has inherited from the thread, you do not need to start newthread in the main thread.
4. Status Control
Knowledge Point: 1. Static Method of sleep: thread -- Exception: interruptedException
2. join method: thread merging, which should have been performed simultaneously by multiple threads. However, after the execution of another thread is complete, the Join method returns to the current thread for execution. It seems that there is only one thread.
3. yield (); giving way to the CPU and giving other threads the chance to execute
5. Thread Synchronization-Lock Mechanism
Public void add (string name ){
Synchronized (this ){
Method body
}
}
Abbreviation:
Publicsynchronizaed void add (string name ){}
Note:
The locked object is not completely locked, but the locked method cannot be accessed. The unlocked method can still be executed. Therefore, if the value is changed, you need to add a lock to each method.
The above are related knowledge about threads. For the soft test, you only need to understand the basic concepts of threads and processes. The specific code does not need to be further understood. In addition, for more information about the operating system, refer to the overview of the operating system, which also involves disk read/write, file read/write, PV operations, mechanisms (producer and consumer issues)