Java Threading Mechanism

Source: Internet
Author: User
Tags mutex

Thread Description:

A thread is a sequential control flow within a program.
The difference between threads and processes:
Each process has its own code and data space (the process context), and there is a significant overhead involved in switching between processes.
Threads can be thought of as lightweight processes, sharing code and data spaces with a class of threads, each with a separate run stack and program counters, and a small overhead for thread switching.

Multi-process:
Multiple tasks that can be run concurrently in the operating system.
Multithreading:
There are multiple sequential streams in the same application that execute concurrently.

Java threads are implemented by the Java.lang.Thread class, and the JVM starts with a thread defined by the main method; You can create a new thread by creating an instance of the thread; Each thread is run () that corresponds to a particular thread object method to complete its operation, the run () method is called the thread body.

Create and start a thread:

The first type:
1. Define the thread class target to implement the Runnable interface (using the Runnable interface to provide shared data for multiple threads), where there is only one method in runnable public void run ();
2.Thread my thread = new thread (target);
3. The thread's static method (Currectthread () method can be used to get a reference to the current thread) in the run () method definition of the class that implements the Runnable interface.
The second type:
1. You can define a subclass of Thread and override its run () Method: Class MyThread extends thread{public void Run () {}};
2. Then generate the object for the class.

Transition of thread State:
                       Blocking                      <-----------------                   scheduling     causes blocked events                  <----       ---->* Blocking status *  Create    * Ready status *    Run status     * End of      ---->       ---->       ---->      start        schedule       Run

* Marked as thread state, arrow indicates conversion process.
The basic method of threading control:

IsAlive () Determines whether the thread is still alive, that is, the thread is not terminated (above blocking, ready, running three states)
GetPriority () Gets the priority of the thread
SetPriority () Sets the priority of the thread
Thread.Sleep () puts the current thread into hibernation and specifies the number of milliseconds to sleep
Join () merges the current thread with the thread that is calling the method, that is, waits for the thread to end, in reply to the current thread's run
Yield () yields the CPU, the current thread enters the ready queue to wait for dispatch
Wait () The current thread enters the object's wait pool
Notify ()/notifyall () wakes up one/So wait thread in the wait pool of the object

Examples of joins:

 Public classTestjoin { Public Static voidMain (string[] args) {MyThread2 T1=NewMyThread2 ("ABCDE");    T1.start (); Try{t1.join (); } Catch(Interruptedexception e) {} for(inti=1;i<=10;i++) {System.out.println ("I am Main thread"); }  }}classMyThread2extendsThread {MyThread2 (String s) {Super(s); }     Public voidrun () { for(intI =1;i<=10;i++) {System.out.println ("I am" +getName ()); Try{sleep (1000); } Catch(interruptedexception e) {return; }    }  }}

The main () method continues only if the T1 run () method is executed.

Java Priority level:

Java provides a thread scheduler to monitor all threads in a program that have entered a ready state after it has been started, and the thread scheduler determines which thread should be called to execute according to the priority of the thread, and the priority of the thread is represented by a number, ranging from 1 to 10, and the default priority of a thread is 5.
thread.min_priority = 1
Thread.max_priority = 10
Thread.norm_priority = 5

Thread synchronization:

In the Java language, the concept of object mutex is introduced to ensure the integrity of the shared data operation; Each object corresponds to a token that can be a mutex; this tag guarantees that only one thread accesses the object at any time, and that the keyword synchronized is used to associate with the object's mutex lock When an object's synchronized is decorated, it indicates that the object can only be accessed by one thread at any one time.


Usage of synchronized:

      synchronized (this) {      }

Synchronized can also be placed in a method health declaration, indicating that the entire method is a synchronous method:

   Public synchronized void Add (String name) {   }

Regardless of whether the Synchronized keyword is added to a method or an object, the lock it obtains is an object, not a piece of code or function as a lock-and the synchronization method is likely to be accessed by other threads ' objects.

 Public classTestsyncImplementsRunnable {Timer timer=NewTimer ();  Public Static voidMain (string[] args) {testsync test=NewTestsync (); Thread T1=NewThread (test); Thread T2=NewThread (test); T1.setname ("T1"); T2.setname ("T2");     T1.start ();  T2.start (); }   Public voidrun () {Timer.add (Thread.CurrentThread (). GetName ()); }}classtimer{Private Static intnum = 0;  Public synchronized voidAdd (String name) {//synchronized (this) {Num + +; Try{Thread.Sleep (1);} Catch(Interruptedexception e) {} System.out.println (name+ "You are the first" +num+ "thread using a timer"); //}  }}

It is important to note that:

1. Two threads cannot execute a method that is declared synchronized in a class at the same time;
2. When a thread is accessing one of the methods of a class that is declared as a synchronized method, other threads can access methods that are not declared as synchronized in the class;
3. It is not possible to have multiple methods declared as synchronized in a class that are executed (one object has only one mutex and needs to wait for another thread to release the mutex before it can be executed).

The difference between wait and sleep:

When you wait, other threads can access the locked object (the object must be locked when the wait method is called).
When sleep is not available, other threads cannot access the locked object.

Examples of deadlocks:
 Public classTestdeadlockImplementsRunnable { Public intFlag = 1; StaticObject O1 =NewObject (), O2 =NewObject ();  Public voidrun () {System.out.println ("Flag=" +flag); if(Flag = = 1) {            synchronized(O1) {Try{Thread.Sleep (500); } Catch(Exception e) {e.printstacktrace (); }                synchronized(O2) {System.out.println ("1"); }            }        }        if(flag = = 0) {            synchronized(O2) {Try{Thread.Sleep (500); } Catch(Exception e) {e.printstacktrace (); }                synchronized(O1) {System.out.println ("0"); }            }        }    }             Public Static voidMain (string[] args) {Testdeadlock TD1=NewTestdeadlock (); Testdeadlock TD2=NewTestdeadlock (); Td1.flag= 1; Td2.flag= 0; Thread T1=NewThread (TD1); Thread T2=NewThread (TD2);        T1.start ();            T2.start (); }}


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.