Java thread basic knowledge point summary

Source: Internet
Author: User
Tags sleep thread class

1. Thread refers to the running process of the program. The multi-threaded mechanism can run multiple program blocks at the same time, which makes the program running more efficient and solves the problems that traditional programming languages cannot solve.

2. To activate the thread in the class, you must first prepare the following two items:
1. This class must be extended from the Thread class to make itself a subclass of it.
2. The thread handler must be included in the run () method.

3. the run () method is a method defined in the Thread class. Therefore, write the program code of the Thread in the run () method. run () method.

4. The Runnable interface declares the abstract run () method. Therefore, the run () method must be explicitly defined in the class that implements the Runnable interface (the run () method must be implemented ).

5. Every thread is in one of the following states before it is created and extinct: Creation, readiness, running, blocking, and termination.

6. Paused threads can be generated in the following situations:
1. When this thread calls the wait () method of the object;
2. When the thread itself calls the sleep () method;
3. When this thread joins () with another thread.

7. Reasons for the disappearance of frozen elements include:
1. If the thread is frozen by the wait () method of the called object, the notify () method of the object can be lifted when it is called;
2. The thread enters the sleep state, but the specified sleep time is reached.

8. When the run () method of a thread ends or the stop () method is called by the thread, the thread enters the extinction state.

9. The sleep () method in the Thread class can be used to control the sleep state of a Thread. The sleep time depends on the parameters in sleep.

10. You can use the join () method to force a line-by-line operation.

11. The join () method throws an InterruptedException exception. Therefore, you must write the join () method in the try-catch block to capture exceptions.

12. when multiple thread objects manipulate the same shared resource, use the synchronized keyword to synchronize the resource. It can be synchronized (this) {code block to be synchronized} or use the synchronized keyword when declaring a method


The following is an example:
 
I. Standard example
 
The MyThreadLocal class is defined, and an object tlt is created for each of the four threads. As a result, the four thread tlt variables are not shared, and the other is used separately, four threads use copies of tlt (clone product ).
 

The code is as follows: Copy code

/**
* The ThreadLocal class is used.
*
* @ Author leizhimin 2010-1-5 10:35:27
*/
Public class MyThreadLocal {
// Defines a ThreadLocal variable to save int or Integer data.
Private ThreadLocal <Integer> tl = new ThreadLocal <Integer> (){
@ Override
Protected Integer initialValue (){
Return 0;
                }
};

Public Integer getNextNum (){
// Obtain the tl value and add 1, and update the t1 value.
Tl. set (tl. get () + 1 );
Return tl. get ();
        }
}
/**
* Test thread
*
* @ Author leizhimin 2010-1-5 10:39:18
*/
Public class TestThread extends Thread {
Private MyThreadLocal tlt = new MyThreadLocal ();

Public TestThread (MyThreadLocal tlt ){
This. tlt = tlt;
        }

@ Override
Public void run (){
For (int I = 0; I <3; I ++ ){
System. out. println (Thread. currentThread (). getName () + "t" + tlt. getNextNum ());
                }
        }
}
/**
* ThreadLocal test
*
* @ Author leizhimin 2010-1-5 10:43:48
*/
Public class Test {
Public static void main (String [] args ){
MyThreadLocal tlt = new MyThreadLocal ();
Thread t1 = new TestThread (tlt );
Thread t2 = new TestThread (tlt );
Thread t3 = new TestThread (tlt );
Thread t4 = new TestThread (tlt );
T1.start ();
T2.start ();
T3.start ();
T4.start ();

        }
}

It can be seen that the three threads are independent numbers and do not affect each other:

Hread-0 1
Thread-1 1
Thread-0 2
Thread-1 2
Thread-0 3
Thread-1 3
Thread-2 1
Thread-3 1
Thread-2 2
Thread-3 2
Thread-2 3
Thread-3 3

Process finished with exit code 0
The tlt object is one, and the nonsense tl object is also one, because the combination relationship is one-to-one. However, as the number of threads increases, the internal Map of the tl object creates many Integer objects. Only Integer and int are used. Therefore, the object attribute of Integer cannot be felt.
 
2. Do not use ThreadLocal
 
If ThreadLocal is not required, you only need to redefine the MyThreadLocal class:

The code is as follows: Copy code

/**
* The ThreadLocal class is used.
*
* @ Author leizhimin 2010-1-5 10:35:27
*/
Public class MyThreadLocal {
Private Integer t1 = 0;
Public Integer getNextNum (){
Return t1 = t1 + 1;
        }

 

//// Defines a ThreadLocal variable to save int or Integer data.
// Private ThreadLocal <Integer> tl = new ThreadLocal <Integer> (){
// @ Override
// Protected Integer initialValue (){
// Return 0;
//}
//};
//
// Public Integer getNextNum (){
/// Obtain the tl value and add 1 to it, and update the t1 value.
// Tl. set (tl. get () + 1 );
// Return tl. get ();
//}
}

Then run the test:
Thread-2 1
Thread-2 2
Thread-1 4
Thread-1 6
Thread-3 3
Thread-3 9
Thread-3 10
Thread-1 8
Thread-0 7
Thread-0 11
Thread-0 12
Thread-2 5

Process finished with exit code 0
From this we can see that the four threads share the tlt variable, and each thread directly modifies the tlt attribute.
 
3. Implement ThreadLocal by yourself
 

The code is as follows: Copy code

Package com. lavasoft. test2;

Import java. util. Collections;
Import java. util. HashMap;
Import java. util. Map;

/**
* The ThreadLocal class is used.
*
* @ Author leizhimin 2010-1-5 10:35:27
*/
Public class MyThreadLocal {

// Defines a ThreadLocal variable to save int or Integer data.
Private com. lavasoft. test2.ThreadLocal <Integer> tl = new com. lavasoft. test2.ThreadLocal <Integer> (){
@ Override
Protected Integer initialValue (){
Return 0;
                }
};

Public Integer getNextNum (){
// Obtain the tl value and add 1, and update the t1 value.
Tl. set (tl. get () + 1 );
Return tl. get ();
        }
}

Class ThreadLocal <T> {
Private Map <Thread, T> map = Collections. synchronizedMap (new HashMap <Thread, T> ());

Public ThreadLocal (){
        }

Protected T initialValue (){
Return null;
        }

Public T get (){
Thread t = Thread. currentThread ();
T obj = map. get (t );
If (obj = null &&! Map. containsKey (t )){
Obj = initialValue ();
Map. put (t, obj );
                }
Return obj;
        }

Public void set (T value ){
Map. put (Thread. currentThread (), value );
        }

Public void remove (){
Map. remove (Thread. currentThread ());
        }
}

Run the test:
Thread-0 1
Thread-0 2
Thread-0 3
Thread-2 1
Thread-2 2
Thread-3 1
Thread-2 3
Thread-3 2
Thread-1 1
Thread-3 3
Thread-1 2
Thread-1 3

Process finished with exit code 0
Unexpectedly, the ThreadLocal version also runs well, implementing the ThreadLocal function in Java API.

Advantages of multithreading:

A. Memory cannot be shared between processes, but it is very easy to share memory between threads.
B. The system creation process needs to re-allocate system resources to the process, but it takes much less to create a thread. Therefore, it is more efficient to use a thread to implement multi-task concurrency than multi-process.
C. Java built-in multi-thread function support, instead of simply serving as the scheduling method of the underlying operating system, thus simplifying Java's multi-thread programming.

Related Article

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.