"Java Basics Summary" multithreading

Source: Internet
Author: User

1. Two ways to implement multithreading in Java
1 //first: Inherit the thread class, overriding the run () method2 classThreadTest1extendsthread{3      Public voidrun () {4String ThreadName =Thread.CurrentThread (). GetName ();5          for(inti=0;i<10;i++){6System.out.println ("ThreadTest1" +threadname+ "Running ... "+i);7         }8     }9 }Ten  One //the second type: Implement the Runnable interface, overriding the run () method A classThreadTest2Implementsrunnable{ -      Public voidrun () { -String ThreadName =Thread.CurrentThread (). GetName (); the          for(inti=0;i<10;i++){ -System.out.println ("ThreadTest2" +threadname+ "Running ... "+i); -         } -     } + } -  +  Public classthread01{ A      Public Static voidMain (string[] args) { atThreadTest1 T1 =NewThreadTest1 (); -ThreadTest1 t2 =NewThreadTest1 (); -Thread t3 =NewThread (NewThreadTest2 ()); //Note  -Thread T4 =NewThread (NewThreadTest2 ()); -          -         //Start () startup thread in T1.start (); - T2.start (); to T3.start (); + T4.start (); -     } the}

In the final analysis, both methods start the thread by invoking the start () method with the thread class or its child class object.

Why use the start () method instead of the run () method to start a thread? because the start () method produces the system resources required to run the thread, schedules it to run, and calls the line Cheng (run () method).

A thread can only be started once, no matter how many times the start () method is called, the result is only one thread.

2. Thread-sharing resources

It is recommended to implement the Runnable interface with the following benefits:

    • Resources can be shared between multiple threads
    • Avoid problems caused by single inheritance
    • Data and code Independence
1 classThreadTest2Implementsrunnable{2     Private intcount=20;//shared Resources3      Public voidrun () {4String ThreadName =Thread.CurrentThread (). GetName ();5          while(count>0){6System.out.println ("ThreadTest2" +threadname+ "sold" +count+ "Ticket");7count--;8         }9     }Ten } One  A  Public classthreaddemo2{ -      Public Static voidMain (string[] args) { -ThreadTest2 t2 =NewThreadTest2 (); the(NewThread (T2, "Window 1") . Start (); -(NewThread (T2, "Window 2") . Start (); -(NewThread (T2, "Window 3") . Start (); -(NewThread (T2, "Window 4") . Start ();  +     } -}

Operation Result:

ThreadTest2 Window 1 SOLD -Number of Tickets ThreadTest2 window 1 sold +Number of Tickets ThreadTest2 window 3 sold -Number of Tickets ThreadTest2 window 2 sold -Number of Tickets ThreadTest2 window 3 sold -Number of Tickets ThreadTest2 window 1 sold -Number of Tickets ThreadTest2 window 1 sold -Number of Tickets ThreadTest2 window 4 sold +Number of Tickets ThreadTest2 window 1 sold -Number of Tickets ThreadTest2 window 3 sold theNumber of Tickets ThreadTest2 window 3 soldTenNumber of Tickets ThreadTest2 window 2 sold -Number of Tickets ThreadTest2 window 2 sold8Number of Tickets ThreadTest2 window 3 sold9Number of Tickets ThreadTest2 window 1 sold OneNumber of Tickets ThreadTest2 window 4 sold ANumber of Tickets ThreadTest2 window 1 sold5Number of Tickets ThreadTest2 window 3 sold6Number of Tickets ThreadTest2 window 2 sold7Number of Tickets ThreadTest2 window 3 sold2Number of Tickets ThreadTest2 window 1 sold3Number of Tickets ThreadTest2 window 4 sold4Number of Tickets ThreadTest2 window 2 sold1Ticket Number

Issue: Multiple windows have sold the same numbered ticket and an access violation has occurred.

3. Thread synchronization

Synchronous synchronized Meaning: coordinated pace, in accordance with the order; synchronous code block; synchronization function

Prerequisites: 2 or more than 2 threads; using the same lock
Role: Ensure that only one thread in the synchronization is running.
Benefits: Addressing thread safety issues
Cons: Multiple threads need to judge locks, consume resources

in Java, this is the concept of a synchronous lock. Any object reference can be used as a synchronous lock.    We can understand the object reference as the memory address of the objects in the memory allocation system. Solution:1) Synchronizing code blockssynchronized(class or object) {code snippet that needs to be synchronized}2) synchronization function (non-static case) Public synchronized voidFun () {code snippet} is equivalent to Public voidFun () {synchronized( This{Code Snippet}} calls the object of this synchronization function as the synchronization lock for this synchronization function. (in the case of static) Public Static synchronized voidFun () {code snippet} when a static variable or static method is loaded into memory, there is no such object in memory, but there must be a corresponding bytecode file for that class (class name).class), the type of the object is class.        The synchronization lock used by the static synchronization function is the bytecode file for the class. 

1 classThreadTestImplementsRunnable2 {3     Private intTicket=50;4      Public voidrun () {5          while(ticket>0){        6String ThreadName =Thread.CurrentThread (). GetName ();7             //Synchronizing code blocks ( the smaller the better)8             synchronized( This){9                 if(ticket>0){TenSystem.out.println (threadname + "Sales Ticket" +ticket); Oneticket--; A                 } -             } -         } the     } - } -  -  Public classthread03{ +      Public Static voidMain (string[] args) { -ThreadTest T =Newthreadtest (); +(NewThread (T, "window a") . Start (); A(NewThread (t, "window B") . Start (); at(NewThread (t, "Window C") . Start (); -(NewThread (t, "window D") . Start (); -     } -}

Operation Result:

Window a sales ticket 50window D Sales ticket49window D Sales ticket48window D Sales ticket47window D Sales ticket46window D Sales ticket45window D Sales ticket44window D Sales ticket43window D Sales ticket42window D Sales ticket41window D Sales ticket40window D Sales ticket39window D Sales ticket38window D Sales ticket37window D Sales ticket36window D Sales ticket35window D Sales ticket34window D Sales ticket33window D Sales ticket32window D Sales ticket31window D Sales ticket30window D Sales ticket29window D Sales ticket28window D Sales ticket27window D Sales ticket26window D Sales ticket25window D Sales ticket24window D Sales ticket23window D Sales ticket22window D Sales ticket21stwindow D Sales ticket20window D Sales ticket19window D Sales ticket18window D Sales ticket17window D Sales ticket16window D Sales ticket15window D Sales ticket14window D Sales ticket13window D Sales ticket12window D Sales ticket11window D Sales ticket10window D Sales ticket9window D Sales ticket8window D Sales ticket7window D Sales ticket6window D Sales ticket5window D Sales ticket4window D Sales ticket3window D Sales ticket2window D Sales ticket1
View Code

4. Thread deadlock

The deadlock phenomenon is the situation that waits for each other
(Deadlock in the operating system) refers to 2 or more processes in the execution process, due to competing resources to create a mutually waiting situation, without external interference, the process can not proceed.
The cause of a deadlock is generally caused by the locking of two objects waiting for each other.
So why would a deadlock occur?

    1. Because of insufficient system resources.
    2. The order in which the process is running is inappropriate.
    3. Improper allocation of resources.

There are four conditions for generating a deadlock:

    1. Mutex condition: The so-called mutex is a process that exclusively resources within a certain time.
    2. Request and hold condition: When a process is blocked by a request for resources, it remains in place for the resources that have been obtained.
    3. Non-deprivation: the process has acquired resources and cannot be forcibly deprived until the end of use.
    4. Cyclic wait condition: a cyclic waiting resource relationship is formed between several processes.

5. Single-Case mode

Features: 1. Private constructor 2. Create a private static reference to your instance in the Class 3. A static public method that takes its own instance as the return type value.

A hungry man class singleton{    private static final Singleton singleinstance = new Singleton ();    Private Singleton () {} public    static Singleton getinstance () {        return singleinstance;    }} 
Lazy class singleton{    private static Singleton singleinstance =null;    Private Singleton () {} public    static synchronized Singleton getinstance () {        if (singleinstance==null {            singleinstance = new Singleton ();} return singleinstance;}}      

6. Thread Communication (Wait () and notify (), Notifyall ())

The state of the thread

  

7. Reentrantlock and condition

View Code

8. Methods for stopping threads (interrupt () and Isinterrupt ())

9. Daemon Threads and Join methods

A daemon is a convenient service for other threads, and the daemon ends up working with the JVM when all the user threads are finished. Thread.setdaemon (true);

public static void main (string[] args) {        thread t3 = new Thread (test2, "thread T3");    T3.start ();    T3.join ();    The main thread waits for this until the T3 thread ends. }

10. Thread priority and yield method

The priority of the thread is low to High: 1-10, priority execution is high, each new thread inherits the parent thread's priority, constant: Thread.min_priority value is 1,thread.max_priority value is 10,thread.norm_ The priority value is 5

void setpriority (priority) int getpriority ()

The yield () method changes the thread from the execution state to the ready state.

"Java Basics Summary" multithreading

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.