Then brother combed Java Knowledge points-multithreading (16)

Source: Internet
Author: User

Creating multithreading
The first way :
① Inheritance: Inherits Thread.
② rewrite: Overriding the Run () method of the Thread class
③ creating: Creating an object of a subclass
④ Call: Call the Start () method of the thread, start this thread, call the Run () method

1 classWorkextendsthread{//① Inheritance2     @Override3     //② rewrite4      Public voidrun () {5        for(inti = 1; i < 5; i++) {6System.out.println (Thread.CurrentThread (). GetName () + ":" +i);7       }8     }9 }Ten  Public Static voidMain (string[] args) { One     //③ Create AWork work =NewWork (); -     //④ Call -    Work.start (); the      for(inti = 1; i < 5; i++) { -System.out.println (Thread.CurrentThread (). GetName () + ":" +i); -     } -}

Output Result:

Main:1main: 2Main:3Main:4thread-0:1thread-0:2thread-0:3 Thread-0:4

Thinking: Change the top start to run, and think about what will happen?

Main:1main: 2Main:3Main:4main:1main:2Main:3  Main:4

Walked two times in main. Because start is the startup thread, run just calls the method normally, and multithreading doesn't matter.


The second method :
① implementing interfaces: Classes that implement runnable interfaces
② implementing an abstract method: Implementing the interface's Run method
③ creating objects: Creating an object of an Runnable interface implementation class
④ into the constructor: the constructor that passes this object as a parameter to the thread, creating a Thread object
⑤ Boot thread: start this thread

1 classWorkImplementsrunnable{//① Implementation Interface2     //② Implementing abstract methods3      Public voidrun () {4       for(inti = one; i < 100; i++) {5System.out.println (Thread.CurrentThread (). GetName () + ":" +i);6       }7     }8 }9 Ten  Public Static voidMain (string[] args) { One     //③ Creating Objects AWork work =NewWork (); -     //④ into the constructor -Thread T1 =NewThread (work); the     //⑤ Start Thread -     T1.start (); -      for(inti = one; i < 100; i++) { -System.out.println (Thread.CurrentThread (). GetName () + ":" +i); +     } -}

Thread (Class) VS Runnable (interface)
①runnable avoids the single inheritance limitations of Java classes, and interfaces can inherit more.
② If multiple threads are working on the same resource, it is more appropriate to use runnable


Common methods for threading thread:
①start (): Starts the thread and executes the appropriate run () method
②run (): Put the child thread to execute code into the run () method
③currentthread (): Static, fetching the current thread
√getname (): Gets the name of this thread
Example: Thread.CurrentThread (). GetName ()

√setname (): Sets the name of the thread

④yield (): Forces the release of the current CPU execution, (for example, the child thread and the main thread both loop output 100 times the number, when the main thread%10==0, call the main thread yield method Thread.CurrentThread (). Yield (), Force the main thread to release CPU execution) It is important to note that the CPU execution of the freed thread does not necessarily mean that other threads will be able to grab the CPU execution right. It is also possible to release the thread to grab the resource again.
⑤join (): invokes the B-thread join (meaning-participating) method in a thread, indicating that when executed to this method, a thread stops executing and B executes after execution.
⑥sleep (): Explicitly let the current thread sleep 1 milliseconds

Set the priority of the thread: High priority can only indicate a high probability of being robbed, does not mean that must be completed first
①getpriority (): Gets the priority of the thread
②setpriority (): Sets the priority of the thread
There are altogether 10 levels. The default is that the attribute in the hierarchy 5,thread is the rank level
Thread Properties:
√max_priority: Highest Thread priority
√min_priority: Lowest Thread priority
√norm_priority: Default Thread Priority
Threads fall into two categories
① Daemon Thread
To serve the user, garbage collection is a typical daemon thread
If the JVM is a daemon thread, the current JVM exits
② User Thread
Threads created by users themselves
User thread--Daemon thread:
by calling Thread.setdaemon (True) before the start () method, you can

The life cycle of a thread: enumeration status represents state

1. New state: A new Thread object was created.
2. Ready state (Runnable): After the thread object is created, other threads call the object's start () method. The state of the thread is located in a pool of running threads that becomes operational and waits for the CPU to be used.
3, running State (Running): The ready state of the thread gets the CPU, executes the program code.
4, blocking State (Blocked): Blocking state is the thread for some reason to abandon the use of the CPU, temporarily stop running. Until the thread is in a ready state, the opportunity to go to the running state is reached. There are three types of blocking:
(i), waiting for blocking: The running thread executes the wait () method, and the JVM puts the thread into the waiting pool.
(ii), synchronous blocking: When a running thread acquires a synchronization lock on an object, the JVM puts the thread into the lock pool if the synchronization lock is occupied by another thread.
(iii), other blocking: The running thread executes the sleep () or join () method, or when an I/O request is made, the JVM will place the thread in a blocked state. When the sleep () state times out, join () waits for the thread to terminate or time out, or the I/O process finishes, the thread is re-entered in a ready state.
5. Dead State (Dead): The thread finishes executing or exits the run () method because of an exception, and the thread ends the life cycle.

Thread Safety
Reason:
Because one thread has not finished executing during the operation of the shared data, another thread is involved,
A security issue exists that results in shared data.
Shared data: Multiple threads work together on the same data (variable)

Solve:
You must have one thread operation to share the data, and other threads have the opportunity to share the data.

How is Java solved?
Mode one: Synchronizing code blocks
Synchronized (Sync monitor) {
Code that needs to be synchronized
}
Sync Block pack who is it? WHO operates the shared data on the package who
Note: In the way of implementation, you can use this to act as a lock, but in the way of inheritance, be cautious with this

Mode two: Synchronous method
Lock for synchronous method: this

 Public void method () {}

Singleton mode: Thread safety

1 classsingleton{2     PrivateSingleton () {3     4     }5     Private StaticSingleton instance =NULL;6      Public StaticSingleton getinstance () {7     if(Instance = =NULL){8       Synchronize (SINGLETON.CALSS) {9         if(Instance = =NULL){TenInstance =NewSingleton (); One         } A       } -     } -     returninstance; the } 

Interview questions:
The bank has an account, with two depositors depositing 3000 yuan to an account, each saving 1000, saving 3 times
To print the account balance after each deposit

Analysis:
What is a shared resource? is obviously an account.
Do I need to use multithreading? Apparently, because there are two depositors.

1 classAccount {2     DoubleBalance = 0;3      Public synchronized voidCunqian (DoubleCRM) {4Balance + =CRM;5System.out.println (Thread.CurrentThread (). GetName () + ":" +balance);6     }7 }8 classCustomerImplementsrunnable{9     Account account ;Ten      PublicCustomer (account account) { One        This. Account =Account ; A     } -     @Override -      Public voidrun () { the        for(inti = 0; I < 3; i++) { -Account.cunqian (1000); -       } -     } + } -  Public Static voidMain (string[] args)throwsException { +Account Account =NewAccount (); ACustomer customer =NewCustomer (account); atThread T1 =NewThread (customer); -     T1.start (); -Thread t2 =NewThread (customer); -     T2.start (); -T1.setname ("Depositor 1"); -T2.setname ("Depositor 2"); in}

The above code needs to be: because it is two classes, it is important to ensure that the shared resource class must not be instantiated multiple times
So make sure that the first class is instantiated when the form parameter is constructed in the second (see Red Mark section)


Thread Communication:
①wait (): Suspends the current thread and discards the CPU and synchronizes resources. Allow other threads to access and modify shared resources while the current prospect is queued for access to resources again
②notify (): Wakes the highest-priority lock in the thread that is waiting to synchronize resources
③notifyall (); Wakes all queued waits for all threads to end the wait

Then brother combed Java Knowledge points-multithreading (16)

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.