I Exception
1.Exception: exception
Compile time exception and runtimeException:
Problems occur during the operation of the program (code writing is not rigorous),
As long as it is not a subclass of RuntimeException, it is a compile time exception;
2. Compile time exception: the exception that needs to be checked before the program runs
Example: in life, "check your tires before a long trip"
Run time exception: in the program, the program code logic problem (the code is not rigorous)
For example, "no zuo no die" in life
3. There are two ways to handle exceptions:
(1) standard format: try catch... finally
Deformation format try{ //Possible problem codes }catch(Exception class name variable name){ //Handling exceptions } ----------------------------------------------------------------------------------------- try{ //Possible problem codes }catch(Exception class name variable name){ //Handling exception 1 }catch(Exception class name variable name){ //Handling exception 2 } ----------------------------------------------------------------------------------------- //Multithreading: jdk5 later: Lock: interface (lock: repeatable mutex) try{ //Possible problem codes }finally{ //Free resources (system resources) }
(2)throws: throws
4. Use try Catch to handle multiple exceptions
jdk7 later
try{ Possible problem codes }catch(Exception class name 1 | Exception class name 2 | Exception class name 3 ...Variable name){ //Exception class name must be the same level Handling exceptions }
5. What is the difference between compile time exceptions and run-time exceptions?
(1) Runtime exception:
The caller can perform display processing (try...catch.../throws) for problems caused by general programmers' loose logical structure
It can also be processed through logical statements without display processing
(2) Compile time exception: the caller must display and handle it. If it is not handled, the compilation cannot pass and the program cannot run
Interview question 1
What's the difference between throws and throw?
(1) Common ground
When they throw an exception, the method that throws the exception is not responsible for handling it. As the name suggests, just throw it and the caller is responsible for handling it.
(2) Distinction
a.throws is used in the method header and represents only the declaration of exceptions,
throw is used inside the method, and the exception object is thrown.
b.throws can throw multiple exceptions at one time,
Throw can only throw one exception
When c.throws throws an exception, its superior (caller) should also declare to throw an exception or catch it, otherwise the compilation will report an error.
throw, you can not declare or capture (this is a very irresponsible way), but the compiler will not report an error.
Interview question 2
If an exception is caught in a method, but the method has a return value type,
If the return statement appears in the catch statement, will the finally code be executed?
If it will be executed, before or after return
public class Test { public static void main(String[] args) { int num = getNum(10) ;// i=10 System.out.println(num); } private static int getNum(int i) { try{ i = 20 ; //i = 20 ; System.out.println(i/0); //Divisor is 0 }catch (ArithmeticException e){ i = 30 ; //i =30 return i ; // Return I = return 30: the return path has been formed in the catch statement, and the return result is 30 }finally { //finally, the code will execute unless the jvm exits i = 40 ; // i = 40 // return i ; } return i; //30 } }
finally, it will execute, but now the code has formed a return path in the catch statement, and it will record that the final return is 30;finally, it is used to release resources, rarely involving business code; Will be executed unless the jvm exits
II thread
1. Thread
Thread: the smallest unit of execution in a program (a task line in a process)
Process: an independent unit of system resources that can be invoked
A process consists of multiple threads. Multiple threads ----- > thread group
Thread dependent process
Single thread: there is always only one path during program execution
Multithreading: there are multiple execution paths during program execution
Concurrency: at the same time at a point in time ----- > is related to cpu performance (number of logical cores of cpu)
Parallel: simultaneously in a time period
2. Construction method of thread class:
Thread(String name): creates a thread class object and sets the name
3. Member method of thread class
public final String getName(): get thread name
public final void setName(String name): sets the thread name
4. Thread priority
Static constant field in Thread class (member variable field)
public static final int MAX_PRIORITY 10 # maximum priority
public static final int MIN_PRIORITY 1 # minimum priority
public static final int NORM_PRIORITY 5# default priority
public final void setPriority(int newPriority): sets the priority of the thread
public final int getPriority(): get priority
The higher the priority: the greater the preemption of CPU execution power
Low priority: the smaller the preemption of CPU execution power
Default priority: more random
5. What is the meaning of multithreading?
A: multithreading features: randomness
Multiple threads are preempting CPU execution rights
Interview question 1
Is the jvm multithreaded?
Is multithreaded:
There are at least two threads
The user thread main, and when the object is created, when the object is used,
The jvm needs to be recycled by the garbage collector for no more reference objects,
Open a garbage collection thread!
Interview question 2
How many thread states are there? Life cycle: from thread creation, ready, execution, to end
Answer: new (new status)
Runnable (execution status)
Blocked
Waiting
TIMED_ Waiting (timeout)
Terminated (dead state)
6. The first step of thread creation method? (only disadvantages, almost no advantages)
(1) declare a class as a subclass of Thread;
(2) this subclass should override the run method of Thread class;
(3) create the current subclass object and start the thread start();
public class MyThread extends Thread { //Override the method of the Thread class @Override public void run() { //In the run method: generally time-consuming operations for(int x = 0 ; x < 200 ; x ++){ System.out.println(x); } } }
public class ThreadDemo { public static void main(String[] args) { //3) Create a subclass object of the Thread class MyThread my1 = new MyThread() ;//First thread object MyThread my2 = new MyThread() ; //Second thread object my1.start();//start(): a jvm calls the underlying run method, and concurrent execution occurs my2.start(); } }
7. The second step of thread creation method?
(1) the user-defined class implements the Runnable interface
(2) Rewrite the run method of the Runnable interface
(3) create the current class object as a resource sharing class
Create Thread class objects respectively and pass resource class objects as parameters
(4) start threads respectively;
public class MyRunnable implements Runnable { @Override public void run() { //Time consuming operation for(int x = 0 ; x < 100 ; x ++){ //public static Thread currentThread() System.out.println(Thread.currentThread().getName()+":"+x); } } }
public class ThreadDemo { public static void main(String[] args) { //You can assign instances of classes (create instances of classes) MyRunnable my = new MyRunnable() ; //Resource class: shared by multiple threads / / concrete class new concrete class //Create two thread class objects Thread t1 = new Thread(my,"Zhang Junjie") ; Thread t2 = new Thread(my,"Gao Yuanyuan") ; //Start threads separately t1.start(); t2.start(); } }
8. Standards for testing multithreading safety issues;
1) Whether it is a multithreaded environment ------------------------------- yes --------------------- cannot be changed. Use multithreaded implementation
2) Whether there is shared data ------------------------------- yes --------------------- there must be shared data
3) Whether there are multiple statements to operate on shared data ----------- yes ----------- solution point
Solution - Java provides synchronization mechanism: synchronize code blocks to wrap multiple pairs of shared data
synchronized(Lock object){ Wrap multiple pairs of shared data }
Lock object: the same lock object must be used by multiple threads, not their own lock objects
Take 100 movie tickets bought from three windows of the cinema as an example
public class SellTicket implements Runnable { //Member variables; 100 tickets public static int tickests = 100 ; //Create a lock object: public Object obj = new Object() ; //t1,t2,t3 @Override public void run() { //Simulation ticket while(true){ //t1,t2,t3 //Solution: //Wrap the operations of multiple statements on shared data //synchronized (new Object()) {/ / lock object: three threads use their own locks //Must be the same lock object synchronized (obj){ //Analog network delay //judge if(tickests>0){ try { Thread.sleep(100); //In milliseconds } catch (InterruptedException e) { e.printStackTrace(); } //Output window information System.out.println(Thread.currentThread().getName()+"The second is being sold"+(tickests--)+"Ticket"); } } } } }
public class SellTicketTest { public static void main(String[] args) { //Create resource class object SellTicket SellTicket st = new SellTicket() ; //Create three thread class objects Thread t1 = new Thread(st,"Window 1") ; Thread t2 = new Thread(st,"Window 2") ; Thread t3 = new Thread(st,"Window 3") ; //Start threads separately t1.start(); t2.start(); t3.start(); } }
9. What is a synchronization method?
If the first sentence of the method body of a method is to synchronize code blocks
You can extract the synchronized keyword onto the method declaration, following the permission modifier
Permission modifier synchronized Return value type method name(Form list){ //Non static synchronization method Business logic... }
Interview questions:
wait() method / notify() method -- also known as "synchronization" - -- > wait for wake-up mechanism
Thread wait / thread wake-up methods are not defined in the thread class, but in the Object class?
It is related to the lock object, which can be any java class object, ---- object (top-level parent class)
syncronized(Lock object){ Lock object.wait() //Lock object notify() }
10. Thread safety problem: it can be solved through synchronization method or synchronization code block, but deadlock may occur during execution
Deadlock problem:
(use the synchronization mechanism to solve thread safety) there is a situation of waiting for each other between threads!
Solution:
Communication between multiple threads: you must use a resource class object, not each thread using its own resource class object!
Use the idea of generator and consumer mode to solve the problem. The prerequisite is that the generator thread and consumer thread must operate on the same resource class object!
10.1
Use the producer and consumer mindset to solve thread deadlock
1)StuffBun package subclass properties
Contains the name of the bun
Size of steamed stuffed bun
2) Producer resource class {SetBun} generates steamed stuffed bun
3) Consumer resource class GetBun uses package
4) Threaddemo: mainuser thread
Follow the above method: simulate the producer to generate data, and the consumer has a problem with the data null---null
The package sub objects operated in the production resource class and the consumer resource class are not the same object!
You can pass the package through the production resource class or the consumer resource class through the construction method
Optimization 1:
Join the while loop to simulate the continuous production and consumption of steamed stuffed buns!
Problem: Data disorder: add synchronization code blocks to each resource class to solve! Package the operations of multiple statements on shared data;
Question:
In the consumer thread where the consumer resource class is located, a large piece of content is output each time:
Randomness of thread execution -- threads seize the execution right of CPU and execute many times in a little time slice
-------------------------------------------------------------------------------------------------------------------------
Optimization 2:
Want to print in sequence
Meat steamed stuffed bun --- big steamed stuffed bun
Steamed stuffed bun --- small steamed stuffed bun
...
Wait() + notify() --- > implement the synchronization mechanism (and signal method at the same time: solve the deadlock problem)
Steamed stuffed bun
public class StuffBun { //Member variables are not privatized String name ;//Type of steamed stuffed bun (meat steamed stuffed bun, vegetable steamed stuffed bun) String bunType ;//Big steamed stuffed bun / small steamed stuffed bun //Definition flag: indicates whether there is package sub data boolean flag ; //The default is false and there is no data }
Consumer resources
public class GetBun implements Runnable { //Declare the variable stu of the package subclass private StuffBun stu ; public GetBun( StuffBun stu){ this.stu = stu ; } @Override public void run() { //Data to be used for simulation // StuffBun stb = new StuffBun() ; //Continuous use of data while(true){ synchronized (stu){ //If there is package data in the current consumption resource class, wait for the consumption data to be used first if(!stu.flag){ //Waiting for data to be used up try { stu.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(stu.name+"---"+stu.bunType); //Change signal value //If the steamed stuffed bun is consumed stu.flag = false ; //Wake up the other thread (producer resource class, don't wait, generate data) stu.notify(); } } } }
Producer resource class
public class SetBun implements Runnable { //Declare this package subclass private StuffBun stu ; public SetBun(StuffBun stu){ this.stu = stu ; } //Define a statistical variable int x = 0 ; @Override public void run() { while(true){ synchronized (stu){ //If the current producer has no statements, it needs to wait for data generation if(stu.flag){ //The lock object calls wait to send that message try { stu.wait();//Release lock object } catch (InterruptedException e) { e.printStackTrace(); } } if(x % 2 == 0){//t1 stu.name = "steamed meat bun" ; stu.bunType = "Big stuffed bun"; }else{ stu.name = "vegetable bun" ; stu.bunType = "Steamed stuffed bun" ; } //If you have data now //Change signal stu.flag = true ;//There are data classes //Notify (wake up) the consumer thread to use the data quickly stu.notify(); //Wake up the other thread } x ++ ; } }
Test class
public class ThreadDemo { public static void main(String[] args) { //Create a package sub object StuffBun sbu = new StuffBun() ; //Same object //Create production resource class object SetBun sb = new SetBun(sbu) ; //Consumer resource class object GetBun gb = new GetBun(sbu) ; //Thread created object Thread t1 = new Thread(sb) ;//The producer thread in which the producer resource class resides Thread t2 = new Thread(gb) ;//The consumer thread where the consumer resource class is located t1.start(); t2.start(); } }
11. Lock
Java. Java is available after JDK5 util. current. locks. Lock: provides a more specific locking operation than the synchronized method (/ synchronized code block)
Multiple threads access concurrently to preempt the shared resource data. Multiple threads can have exclusive access to a shared resource through lock, which will not cause security problems
Lock is an interface
void lock() get lock
void unlock() attempted to release the lock
Provide a specific sub implementation class: ReentrantLock
Realize movie ticket sales: three windows sell 100 tickets (thread creation method 2)
import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class SellTicket implements Runnable { //Define 100 tickets private static int tickets = 100 ; //Create a lock object Lock lock = new ReentrantLock() ; @Override public void run() { //Simulation one has only one ticket while(true){ //Get lock through lock object -- > lock.lock(); //try... catch... Finally: exception caught //Use try finally try{ //judge if(tickets>0){ //Sleep for 100 milliseconds try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"The second is being sold"+(tickets--)+"Ticket"); }else{ break ; } }finally { //Release lock lock.unlock(); } } } }
public class LockDemo { public static void main(String[] args) { //Create shared resource class object SellTicket st = new SellTicket() ; //Create three thread class objects Thread t1 = new Thread(st,"Window 1") ; Thread t2 = new Thread(st,"Window 2") ; Thread t3 = new Thread(st,"Window 3") ; //Start thread t1.start(); t2.start(); t3.start(); } }
12. Thread group ThreadGroup (just understand)
A thread group represents a group of threads. In addition, thread groups can include other thread groups
Thread group: all threads can be added to a group for easy management. After the thread is started and terminated, this thread object will not be reused in memory
13. Thread pool
Thread pool belongs to "pool" technology;
Features: create a fixed number of reusable threads in memory. The current thread terminates after execution and will not be recycled. Return to the thread pool again and wait for the next utilization;
Disadvantages: high maintenance cost;
ExecutorService --- interface
(1)Exceutors
< 1 > create a fixed number of reusable threads, and the return value is the thread pool object
public static ExecutorService newFixedThreadPool(int nThreads)
(2)ExecutorService
< 1 > submit queue tasks (multiple threads execute concurrently)
<T> Future<T> submit(Callable<T> task)
< 2 > submit the value, return the task to execute, and return the Future representing the pending result of the task
Future<?> submit(Runnable task)
Return value of submit: the result of asynchronous calculation. If no calculation is performed, there is no need to return the result
MyCallable
import java.util.concurrent.Callable; public class MyCallable implements Callable { @Override public Object call() throws Exception { for(int x = 0 ; x < 100 ; x++){ System.out.println(Thread.currentThread().getName()+":"+x); } return null; } }
ThreadPoolDemo
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class ThreadPoolDemo { public static void main(String[] args) { //Create a thread pool object through the factory class ExecutorService threadPool = Executors.newFixedThreadPool(2); threadPool.submit(new MyCallable()) ; threadPool.submit(new MyCallable()) ; //void shutdown() closes the thread pool threadPool.shutdown(); } }