<> one , Create thread mode
1, Creation of Multithread , Mode one : Inherited from Thread class * 1. Create a Thread Subclasses of classes * 2. rewrite Thread Class run() -->
Declare the operations performed by this thread in the run() in * 3. establish Thread Object of a subclass of class * 4. Called through this object start() 2
, The second way to create Multithread : realization Runnable Interface * 1. Create an implementation Runnable Class of interface * 2. Implementation class to implement Runnable Abstract methods in :run()
* 3. Create an object that implements the class * 4. Pass this object as a parameter to Thread Class , establish Thread Class * 5. adopt Thread Class start
() * * * Compare two ways to create threads . * Under development : Preference : realization Runnable Interface mode * reason :1. The way of implementation is not limited by the single inheritance of class * 2.
The implementation method is more suitable to deal with the situation that multiple threads have shared data .* * contact :public class Thread implements Runnable *
Similarities : Both methods need to be rewritten run(), The thread on which the logic is to be executed run() in . * 3, Three ways to create threads : realization Callable Interface . --- JDK 5.0 newly added
* 1. Create an implementation Callable Implementation class of * 2. realization call method , Declare the operations that this thread needs to perform in the call() in * 3. establish Callable The object of the interface implementation class
* 4. Put this Callable The object of the interface implementation class is passed to the FutureTask In the constructors , establish FutureTask Object of * 5.
take FutureTask Is passed as a parameter to the Thread Class , establish Thread object , And call start() * 6.
obtain Callable in call Method /** * Three ways to create threads : realization Callable Interface . --- JDK 5.0 newly added * * *
How to understand implementation Callable Interface to create a multithread than the implementation Runnable Interface to create a powerful way of multithreading ? * 1. call() Can have a return value . * 2.
call() You can throw an exception , Captured by outside operations , Get exception information * 3. Callable It supports generics * * @author shkstart *
@create 2019-02-15 afternoon 6:01 */ //1. Create an implementation Callable Implementation class of class NumThread implements
Callable{ //2. realization call method , Declare the operations that this thread needs to perform in the call() in @Override public Object call()
throws Exception { int sum = 0; for (int i = 1; i <= 100; i++) { if(i % 2 == 0){
System.out.println(i); sum += i; } } return sum; } } public class ThreadNew {
public static void main(String[] args) { //3. establish Callable The object of the interface implementation class NumThread
numThread= new NumThread();
//4. Put this Callable The object of the interface implementation class is passed to the FutureTask In the constructors , establish FutureTask Object of FutureTask futureTask
= new FutureTask(numThread);
//5. take FutureTask Is passed as a parameter to the Thread Class , establish Thread object , And call start() new Thread(
futureTask).start(); try { //6. obtain Callable in call Method
//get() The return value is FutureTask Constructor parameters Callable Implementation of class rewriting call() Return value of . Object sum = futureTask.get
(); System.out.println(" The sum is :" + sum); } catch (InterruptedException e) { e.
printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } }
import java.util.concurrent.ExecutorService; import java.util.concurrent.
Executors; import java.util.concurrent.ThreadPoolExecutor; 4, Four ways to create threads : Using thread pool /**
* Four ways to create threads : Using thread pool * * benefit : * 1. Improve response speed ( Reduces the time to create new threads ) *
2. Reduce resource consumption ( Reusing threads in thread pool , You don't need to create it every time ) * 3. Easy for thread management * corePoolSize: Size of the core pool *
maximumPoolSize: Maximum number of threads * keepAliveTime: How long will the thread terminate when it has no task * * *
Interview questions : There are several ways to create multithreading ? Four ! * @author shkstart * @create 2019-02-15 afternoon 6:30 */ class
NumberThread implements Runnable{ @Override public void run() { for(int i = 0;i
<= 100;i++){ if(i % 2 == 0){ System.out.println(Thread.currentThread().getName()
+ ": " + i); } } } } class NumberThread1 implements Runnable{ @Override public
void run() { for(int i = 0;i <= 100;i++){ if(i % 2 != 0){ System.out.println(
Thread.currentThread().getName() + ": " + i); } } } } public class ThreadPool {
public static void main(String[] args) { //1. Provides a thread pool for the specified number of threads ExecutorService
service= Executors.newFixedThreadPool(10); ThreadPoolExecutor service1 = (
ThreadPoolExecutor) service; // Set the properties of the thread pool //
System.out.println(service.getClass()); // service1.setCorePoolSize(15); //
service1.setKeepAliveTime(); //2. Performs the operation of the specified thread . Need to provide implementation Runnable Interface or Callable The object of the interface implementation class
service.execute(new NumberThread());// Suitable for Runnable service.execute(new
NumberThread1());// Suitable for Runnable // service.submit(Callable
callable);// Suitable for use in Callable //3. Close connection pool service.shutdown(); } }
<> two ,, Common methods of thread
* 1. start(): Start the current thread ; Call the run() * 2. run():
It usually needs to be rewritten Thread Class , Declare the operation to be performed by the created thread in this method * 3. currentThread(): Static method , Returns the thread executing the current code * 4.
getName(): Gets the name of the current thread * 5. setName(): Sets the name of the current thread * 6. yield(): Release current cpu The right of execution * 7. join(
): In thread a Calling thread b Of join(), At this point, the thread a It's blocked , Until thread b After full implementation , thread a just * End blocking . * 8. stop():
Deprecated . When this method is executed , Force end of current thread .* 9. sleep(long millitime):
Let the current thread “ sleep ” designated millitime millisecond . In the specified millitime In milliseconds , current * The thread is blocked . * 10. isAlive():
Determine whether the current thread is alive or not * * * thread priority : * 1. * MAX_PRIORITY:10 * MIN _PRIORITY:1 *
NORM_PRIORITY:5 --> Default Priority * 2. How to get and set the priority of the current thread : * getPriority(): Gets the priority of the thread *
setPriority(int p): Set the priority of the thread * *
explain : High priority threads should preempt low priority threads cpu The right of execution . But only in terms of probability , High priority threads have high probability *
Be executed . It doesn't mean that only after the high priority thread has finished executing , Only low priority threads execute .
<> three , Thread safety
one , Synchronous code block solution * example : Create three windows to sell tickets , The total number of votes was 100 Zhang . Use implementation Runnable Interface mode * * 1. problem : In the process of selling tickets , There was a heavy vote , Wrong ticket -->
There is a thread security problem * 2. Causes of problems : When a thread operates a ticket , When the operation has not completed , Other threads are involved , Also operate tickets . * 3.
How to solve it : When a thread a In operation ticket When I was young , Other threads cannot participate . Until thread a It's over ticket Time , other *
Thread can start operation ticket. In this case, even if the thread a There's a jam , It can't be changed .* * * 4. stay Java in , We use the synchronization mechanism , To solve the problem of thread security . * *
Mode one : Synchronization code block * * synchronized( Synchronization monitor ){ * // Code that needs to be synchronized * * } * explain :1.
Code for operating shared data , The code that needs to be synchronized .--> Can't contain too much code , Also can't contain less code . * 2.
shared data : Variables operated by multiple threads . such as :ticket It's sharing data .* 3. Synchronization monitor , be commonly called : lock . Object of any class , Can be used as a lock . *
requirement : Multiple threads must share the same lock .* * supplement : In the implementation Runnable Interface to create multithreading , We can consider using it this Act as a synchronization monitor . * Mode 2 : Synchronization method .
* If the code that operates on the shared data is completely declared in a method , We might as well synchronize this method declaration . * * * 5. How to synchronize , The thread security problem is solved .--- benefit *
When operating synchronization code , Only one thread can participate , Other threads are waiting . Equivalent to a single threaded process , Low efficiency .--- limitations * Using synchronous code blocks to solve inheritance Thread The thread safety of class
* * example : Create three windows to sell tickets , The total number of votes was 100 Zhang . Use inheritance Thread Way of class * * explain : In succession Thread Class to create multithreading , Use with caution this
Act as a synchronization monitor , Consider using the current class as the synchronization monitor .1, Use inheritance Thread The way important : use Window.clss As synchronization lock , reason : Because every one of us this
It's not the same object , Because we created three windows , So if you want to use Window.clss To act as the only lock ; public class Windows extends
Thread { private static int ticket = 100; // Multiple Thread Object to share ticket ticket // private
static Object obj = new Object(); // Need to add static, Because the synchronization monitor is unique @Override public
void run() { while (true) { // synchronized (obj) { // correct // synchronized
(this) { // The wrong way , Use inheritance to create thread, because this Not the same object , Cannot act as a synchronization lock for shared resources synchronized (Window.
class) { // Class object , It will load only once , So it's the only one if (ticket > 0) { try { Thread.sleep(100); }
catch (InterruptedException e) { e.printStackTrace(); } System.out.println(
Thread.currentThread().getName() + ": Selling tickets , The ticket number is : " + ticket); ticket--; } else {
break; } } } } } public class WindowsTest2 { public static void main(String[]
args) { Windows t1 = new Windows(); Windows t2 = new Windows(); Windows t3 = new
Windows(); t1.setName(" window 1"); t2.setName(" window 2"); t3.setName(" window 3"); t1.start();
t2.start(); t3.start(); } } 2, Use implementation Runnable mode a key : Because only one was created Window object , All threads can share the object ,
So use this, Act as synchronization lock public class Windows1 implements Runnable { private int ticket =
100; @Override public void run() { while (true) { // Any object can act as its object Synchronization monitor ,
Because an implementation is always created Rnnable Examples of interfaces ; synchronized (this) { if (ticket > 0) { try { Thread.
sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } System.out.
println(Thread.currentThread().getName() + " Selling tickets , The ticket number is : " + ticket); ticket--; }
else { break; } } } } } public class WindowsTest1 { public static void main(
String[] args) { Windows1 w = new Windows1(); Thread t1 = new Thread(w); Thread
t2= new Thread(w); Thread t3 = new Thread(w); t1.setName(" window 1"); t2.setName(
" window 2"); t3.setName(" window 3"); t1.start(); t2.start(); t3.start(); } } two , Synchronization method a key :
* Using synchronization method to solve the problem of implementation Runnable Thread safety of interface * * Summary of synchronization methods : * 1. The synchronization method still involves the synchronization monitor , It just doesn't need to be explicitly declared . *
2. Non static synchronization method , The synchronization monitor is :this * Static synchronization method , The synchronization monitor is : The current class itself a key : stay synchronized In front of it static,
If it is a static synchronization method , All objects are shared ; amount to Xxx.class The way 1, By inheritance Thread To achieve thread synchronization : // private
synchronized void show () { // At this point, the synchronization lock is not unique . private static synchronized void
show() { // The lock is Current class object , Xxx.class if (ticket > 0) { try { Thread.sleep(100); }
catch (InterruptedException e) { e.printStackTrace(); } System.out.println(
Thread.currentThread().getName() + ": Selling tickets , The ticket number is : " + ticket); ticket--; } } a key :
Just add synchronized, Because only one is created window object , So there's no need to add static, amount to this 2, Through implementation Runnable Interface to create threads :
private synchronized void show() { // Synchronization monitor ( Synchronization lock ) namely this if (ticket > 0) { try {
Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); }
System.out.println(Thread.currentThread().getName() + " Selling tickets , The ticket number is : " + ticket);
ticket--; } } three , Three ways to solve thread safety problem :Lock lock --- JDK5.0 newly added * * 1. Interview questions :synchronized And
Lock The similarities and differences of ?* identical : Both can solve the problem of thread safety * Different :synchronized After executing the corresponding synchronization code , Automatic release synchronization monitor *
Lock Manual start synchronization is required (lock()), At the same time, the end of synchronization also needs to be realized manually (unlock()) * * 2. Priority order : * Lock ->
Synchronization code block ( It has entered the method body , Corresponding resources are allocated )-> Synchronization method ( Outside the method body ) * * * Interview questions : How to solve the problem of thread safety ? There are several ways
<> four , Thread communication problem
Examples of thread communication : Printing with two threads 1-100. thread 1, thread 2 Alternate printing * * Three methods involved : * wait():
Once this method is executed , The current thread is blocked , And release the synchronization monitor .* notify():
Once this method is executed , Will wake up wait A thread of . If more than one thread is wait, Just wake up the one with the highest priority .* notifyAll():
Once this method is executed , Will wake up all the people who have been killed wait Thread of .* * explain : * 1.wait(),notify(),notifyAll()
Three methods must be used in synchronous code blocks or synchronous methods .* 2.wait(),notify(),notifyAll()
The caller of the three methods must be a synchronization code block or a synchronization monitor in a synchronization method .* otherwise , There will be IllegalMonitorStateException abnormal * 3.wait(),
notify(),notifyAll() Three methods are defined in java.lang.Object In class . * * Interview questions :sleep() and wait() The similarities and differences of ? *
1. Similarities : Once the method is implemented , Can make the current thread into a blocking state . * 2. difference :1) The positions of the two method declarations are different :Thread Class sleep() ,
Object Class wait() * 2) The requirements for calling are different :sleep() It can be called in any scenario . wait() Must be used in a synchronization block or synchronization method * 3
) About releasing synchronization monitor : If both methods are used in synchronous code blocks or synchronous methods ,sleep() The lock will not be released ,wait() It will release the lock . class Thread1
implements Runnable { private int number = 1; @Override public void run() {
while (true) { synchronized (this) { this.notify(); // Awakened by wait() Thread of if (number
<= 100) { try { Thread.sleep(50); } catch (InterruptedException e) { e.
printStackTrace(); } System.out.println(Thread.currentThread().getName() + ":
number" + number); number++; try { // call wait() Method thread , Enter the blocking state this.wait(); } catch
(InterruptedException e) { e.printStackTrace(); } } else { break; } } } } }

Technology