I have been dealing with multithreading for a long time and have done many things, but I always feel that it is not so easy to use. During debugging, I often worry about synchronization issues, think of the phrase "the programmer is most afraid of his own code.
One day, I thought it was time to figure out the problem. So I went online to find the relevant content and I couldn't find the result at this stage, it's not that simple, it's just a matter of writing.
I finally figured out what I thought was really different from the truth. think of the time you spent, and I think it is a little too much, so I will write it out to prevent myself from forgetting it later, the second is to leave a reference for people like me who seem to understand or not.
If you want to talk less, go to the subject!
Start with thread creation. There are two ways to create a thread:
One is inherited from the Thread class. The Thread class is a specific class, that is, it is not an abstract class, which encapsulates the thread behavior. To create a thread, the programmer must create a new class to export from the Thread class. Programmers can do useful work by overwriting the run () function of thread. Instead of calling this function directly, you can call the START () function of thread before calling run ().
For example:
Public class test extends thread {
Public test (){
}
Public static void main (string ARGs []) {
Test T1 = new test ();
Test t2 = new test ();
T1.start ();
T2.start ();
}
Public void run (){
// Do thread's things
}
}
The other is to implement the runnable interface, which has only one function, run (), which must be implemented by the class that implements this interface.
For example:
Public class test implements runnable {
Thread thread1;
Thread thread2;
Public test (){
Thread1 = new thread (this, "1 ");
Thread2 = new thread (this, "2 ");
}
Public static void main (string ARGs []) {
Test T = new test ();
T. startthreads ();
}
Public void run (){
// Do thread's things
}
Public void startthreads (){
Thread1.start ();
Thread2.start ();
}
}
The two creation methods do not seem to be much different, but if they are unclear, they may make a mess of your program. The two have the following differences:
1. When you want to inherit from another class, you can only use the latter method.
2. first, because it inherits from the thread and only creates its own object, but in terms of quantity, it requires several threads to create several own objects. Second, it only creates one own object, but several thread objects are created. the major difference between the two methods lies in this: If you create several own objects in the first method and start (), you will find that synchronized does not work, the code block or method that has been locked can have several threads at the same time, and the same variable can have several threads to change it at the same time. (For example, the following code) This is because, in this program, although you have initiated several threads, you have also created several objects, and each thread corresponds to each object, that is, every thread changes and occupies a different object, so there are several threads entering a method at the same time. In fact, it is not a method, but the same method of different objects. So, if you want to lock the method at this time, you can only declare the method or variable as static. After adding static, you will find that the thread can manage the method again, at the same time, there cannot be two threads entering the same method. That is because not every object has a method, but all objects share a method. This method is a static method.
If you use the second method to use the thread, the above situation will not occur, because at this time, you only create one own object, so, attributes and methods of the object are common to the thread.
Therefore, we recommend that you use the second method to use the thread.
Public class mainthread extends thread {
Int I = 0;
Public static void main (string ARGs []) {
Mainthread M1 = new mainthread ();
Mainthread m2 = new mainthread ();
Mainthread m3 = new mainthread ();
Mainthread M4 = new mainthread ();
Mainthread M5 = new mainthread ();
Mainthread M6 = new mainthread ();
M1.start ();
M2.start ();
M3.start ();
M4.start ();
M5.start ();
M6.start ();
}
Public synchronized void T1 (){
I = ++ I;
Try {
Thread. Sleep (500 );
}
Catch (exception e ){}
// Each thread enters its own T1 () method and prints the corresponding I
System. Out. println (thread. currentthread (). getname () + "" + I );
}
Public void run (){
Synchronized (this ){
While (true ){
T1 ();
}
}
}
}
Here are four synchronized usage methods:
1. used for method declaration, placed after the range operator (public, etc.), before the return type declaration (void, etc. that is, only one thread can enter this method at a time. If other threads want to call this method at this time, they can only wait in queue. After the current thread (that is, the thread inside the Synchronized Method) executes this method, other threads can enter.
For example:
Public synchronized void synmethod (){
// Method body
}
2. For a code block, synchronized is followed by parentheses and contains variables. In this way, only one thread enters the code block at a time. For example:
Public int synmethod (INT A1 ){
Synchronized (A1 ){
// Only one thread can enter
}
}
3. Synchronized is followed by an object in parentheses. At this time, the thread obtains an object lock. For example:
Public class mythread implements runnable {
Public static void main (string ARGs []) {
Mythread Mt = new mythread ();
Thread T1 = new thread (MT, "T1 ");
Thread t2 = new thread (MT, "T2 ");
Thread T3 = new thread (MT, "T3 ");
Thread t4 = new thread (MT, "T4 ");
Thread T5 = new thread (MT, "T5 ");
Thread T6 = new thread (MT, "T6 ");
T1.start ();
T2.start ();
T3.start ();
T4.start ();
T5.start ();
T6.start ();
}
Public void run (){
Synchronized (this ){
System. Out. println (thread. currentthread (). getname ());
}
}
}
For 3, if the thread enters, the object lock will be obtained, and no operations can be performed by other threads on all objects of this class. locking at the object level is usually a rough method. Why is it necessary to lock the entire object and not allow other threads to temporarily use other Synchronization Methods in the object to access Shared resources? If an object has multiple resources, you do not need to lock all threads out to allow a thread to use some of the resources. Because each object has a lock, you can use a virtual object to lock it as follows:
Class finegrainlock {
Mymemberclass X, Y;
Object xlock = new object (), ylock = new object ();
Public void Foo (){
Synchronized (xlock ){
// Access X here
}
// Do something here-but don't use shared resources
Synchronized (ylock ){
// Access y here
}
}
Public void bar (){
Synchronized (this ){
// Access both X and Y here
}
// Do something here-but don't use shared resources
}
}
4. Synchronized is followed by a class in brackets. For example:
Class arraywithlockorder {
Private Static long num_locks = 0;
Private long lock_order;
Private int [] arr;
Public arraywithlockorder (INT [])
{
Arr =;
Synchronized (arraywithlockorder. Class) {// ------------------------------------------- here
Num_locks ++; // Number of locks plus 1.
Lock_order = num_locks; // set a unique lock_order for this object instance.
}
}
Public long lockorder ()
{
Return lock_order;
}
Public int [] array ()
{
Return arr;
}
}
Class someclass implements runnable
{
Public int sumarrays (arraywithlockorder A1,
Arraywithlockorder A2)
{
Int value = 0;
Arraywithlockorder first = A1; // reserve
Arraywithlockorder last = a2; // local copy.
Int size = a1.array (). length;
If (size = a2.array (). length)
{
If (a1.lockorder ()> a2.lockorder () // confirm and set the object lock
{// Order.
First = a2;
Last = A1;
}
Synchronized (first) {// lock objects in the correct order.
Synchronized (last ){
Int [] arr1 = a1.array ();
Int [] arr2 = a2.array ();
For (INT I = 0; I <size; I ++)
Value + = arr1 [I] + arr2 [I];
}
}
}
Return value;
}
Public void run (){
//...
}
}
For thread 4, if the thread enters, all operations of the thread in this class cannot be performed, including static variables and static methods. In fact, for synchronization of code blocks containing static methods and static variables, we usually use 4 to lock.
Relationship between the above four types:
A lock is associated with an object. Each object has a lock. To execute the synchronized statement, the thread must be able to obtain the lock of the object specified by the expression in the synchronized statement. An object has only one lock, after being obtained by a thread, it no longer owns the lock. After the thread executes the synchronized statement, it returns the lock to the object.
You can declare a method as a synchronous method by adding the synchronized modifier before the method. The synchronization method obtains a lock before execution. If this is a class method, the obtained lock is the class Object lock related to the class of the declared method. If this is an instance method, the lock is the lock of this object.
The following describes some common methods:
Wait (), wait (long), Y (), policyall () and other methods are the instance methods of the current class,
Wait () is used to release the lock for the thread holding the object lock;
Wait (long) is used to obtain the lock again after the thread holding the object lock is released for long (milliseconds). Wait () is equivalent to wait (0;
Y () is to wake up a thread waiting for the lock of this object. If there are more than one waiting thread, the wake-up thread is determined by JVM;
Policyall is used to wake up all threads waiting for the lock of this object.
Here I also reiterate that we should first use the yyall () method, because it is easier for the JVM to find the most appropriate thread to wake up than to wake up a thread.
The preceding method can only be used in the current thread. Otherwise, the runtime error java. Lang. illegalmonitorstateexception: current thread not owner is reported.
Next, let's talk about the relationships between synchronized, wait (), and notify:
1. Where synchronized exists, wait and notify may not be available.
2. with wait, synchronized must be used in zooy. this is because wait and notify are not thread classes, but methods that every object has. Moreover, these two methods are related to the object lock. Where there is a lock, there must be synchronized.
In addition, note that if you want to use the notify and wait methods together, you must first call notify and then call wait, this thread is no longer the current thread. For example:
/**
* Title: jdeveloper's Java projdect
* Description: N/
* Copyright: Copyright (c) 2001
* Company: Soho http://www.ChinaJavaWorld.com.
* @ Author jdeveloper@21cn.com
* @ Version 1.0
*/
Import java. Lang. runnable;
Import java. Lang. thread;
Public class demothread
Implements runnable {
Public demothread (){
Testthread testthread1 = new testthread (this, "1 ");
Testthread testthread2 = new testthread (this, "2 ");
Testthread2.start ();
Testthread1.start ();
}
Public static void main (string [] ARGs ){
Demothread demothread1 = new demothread ();
}
Public void run (){
Testthread t = (testthread) thread. currentthread ();
Try {
If (! T. getname (). inclusignorecase ("1 ")){
Synchronized (this ){
Wait ();
}
}
While (true ){
System. Out. println ("@ time in thread" + T. getname () + "=" +
T. increasetime ());
If (T. gettime () % 10 = 0 ){
Synchronized (this ){
System. out. println ("************************************* ***");
Notify ();
If (T. gettime () = 100)
Break;
Wait ();
}
}
}
}
Catch (exception e ){
E. printstacktrace ();
}
}
}
Class testthread
Extends thread {
Private int time = 0;
Public testthread (runnable R, string name ){
Super (R, name );
}
Public int gettime (){
Return time;
}
Public int increasetime (){
Return ++ time;
}
}
The following describes the relationship between producers and consumers:
Public class test {
Public static void main (string ARGs []) {
Semaphore S = new semaphore (1 );
Thread T1 = new thread (S, "producer1 ");
Thread t2 = new thread (S, "producer2 ");
Thread T3 = new thread (S, "producer3 ");
Thread t4 = new thread (S, "consumer1 ");
Thread T5 = new thread (S, "consumer2 ");
Thread T6 = new thread (S, "consumer3 ");
T1.start ();
T2.start ();
T3.start ();
T4.start ();
T5.start ();
T6.start ();
}
}
Class semaphore
Implements runnable {
Private int count;
Public semaphore (int n ){
This. Count = N;
}
Public synchronized void acquire (){
While (COUNT = 0 ){
Try {
Wait ();
}
Catch (interruptedexception e ){
// Keep trying
}
}
Count --;
}
Public synchronized void release (){
While (COUNT = 10 ){
Try {
Wait ();
}
Catch (interruptedexception e ){
// Keep trying
}
}
Count ++;
Policyall (); // alert a thread that's blocking on this semaphore
}
Public void run (){
While (true ){
If (thread. currentthread (). getname (). substring (0, 8). inclusignorecase ("consumer ")){
Acquire ();
}
Else if (thread. currentthread (). getname (). substring (). equalsignorecase ("producer ")){
Release ();
}
System. Out. println (thread. currentthread (). getname () + "" + count );
}
}
}
There is generally no conflict between producer production and consumer consumption, but when the inventory is 0, the consumer cannot consume it, but when the inventory is the upper limit (10 here, producers cannot produce either. please study the above program, and you will certainly make a lot better than before.
The code above demonstrates that synchronized has no absolute relationship with wait and notify. In the methods and code blocks declared by synchronized, you do not need to use methods such as wait and notify. However, if a thread has a certain contention for a certain resource, you must put the thread into waiting or waking up in due time.