Summary of this week
1, linklist
1. Characteristics
Thread unsafe classes with high execution efficiency
Link list structure, slow query, add and delete blocks
2. Unique function
public void addFirst(Object e): inserts an element at the beginning of the list
public void addLast(Object e): append the element to the end of the list
public Object getFirst(); Gets the first element of the list
public Object getLast(): get the last element of the list
public Object removeFirst(): deletes the first element of the list and gets the first element
public Object removeLast(): deletes the last element of the list and gets the last element
public class LinkedListDemo { public static void main(String[] args) { //Create a LinkedList collection object LinkedList<String> link = new LinkedList<>() ; //Add element // public void addFirst(Object e): inserts an element at the beginning of the list link.addFirst("hello") ; link.addFirst("world") ; link.addFirst("JavaEE") ; link.addFirst("Android") ; link.addLast("Php") ; //public Object getFirst(): get the first element of the list System.out.println(link.getFirst()); System.out.println(link.getLast()); // Deletes the first element of the list and gets the first element System.out.println(link.removeFirst()); // Deletes the last element of the list and gets the last element System.out.println(link.removeLast()); System.out.println(link); } }
2, Set set
1. Characteristics
Out of order, inconsistent storage and retrieval, which can ensure the uniqueness of elements
2. Sub implementation class
1)HashSet
Overview: the iterative order of set is not guaranteed
The underlying data structure is a hash table (bucket structure). It is a thread unsafe class. It is not synchronized and has high execution efficiency
How to ensure element uniqueness?
The underlying data structure is a hash table (elements are arrays of linked lists)
Hash tables depend on hash value storage
Add function underlying dependency method: int hashCode()
boolean equals(Object obj)
2)linkedHsahSet
Overview: elements are ordered and unique
The order of elements is guaranteed by the linked list
The unique element is guaranteed by the hash table
3. TreeSet class
TreeSet set: unordered, element unique
The bottom layer depends on the TreeMap set. The red black tree structure (also known as "self balanced binary tree structure") can realize the natural sorting of maps and the sorting of comparators, depending on the construction method used
Construction method:
public TreeSet(): construct an empty tree to realize the natural sorting of elements (depending on whether the stored element type can implement the Comparable interface)
Natural sorting - the TreeSet parameterless construction method executed by "and the precondition is that the current storage type must implement the Comparable interface
public class TreeSetDemo { public static void main(String[] args) { //Integer type TreeSet<Integer> ts = new TreeSet<>() ; //The Intger element implements the Comparable interface -- it can be sorted naturally according to the elements (ascending by default) //Add element ts.add(85) ; ts.add(17) ; ts.add(17) ; ts.add(21) ; ts.add(65) ; ts.add(23) ; ts.add(94) ; ts.add(19) ; //Traversal set TreeSet for(Integer i:ts){ System.out.println(i); } } }
TreeSet enables two sorts:
Natural sorting and comparator sorting depend on the construction method
Natural sorting:
TreeSet < E > (), type E must implement the Comparable interface and realize natural sorting (implement CompareTo (T))
Comparator sort:
public TreeSet(Comparator<? super E> comparator)
Comparator is an interface type
1) Customize a class to implement the Comparator interface and override the compare method
2) Anonymous inner class using interface
Generic advanced wildcard
- <?> : Any Java type, including Object
- <? Super E >: upper limit: e type and e parent class
- <? Extensions E >: down limit: e and its subclasses
Define several students and sort them by age
public class Student { private String name ;//full name private int age ;//Age public Student() { } public Student(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age=" + age + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Student student = (Student) o; if (age != student.age) return false; return name.equals(student.name); } @Override public int hashCode() { int result = name.hashCode(); result = 31 * result + age; return result; } }
public class TreeSetDemo { public static void main(String[] args) { TreeSet<Student> ts = new TreeSet<>(new Comparator<Student>() { @Override public int compare(Student s1, Student s2) { //Main conditions: sort according to the age of students from small to large //S1 --- > is this in the natural sorting just now //S2 --- > is s in the natural sorting just now int num = s1.getAge() - s2.getAge() ; //If the age is the same, compare the names int num2 = (num==0)? (s1.getName().compareTo(s2.getName())): num ; return num2; } }) ; Student s1 = new Student("zhangsan",21) ; Student s2 = new Student("liumei",19) ; Student s3 = new Student("wangtian",23) ; Student s4 = new Student("lixiao",15) ; Student s5 = new Student("abcd",20) ; Student s6 = new Student("jiege",25) ; ts.add(s1) ; ts.add(s2) ; ts.add(s3) ; ts.add(s4) ; ts.add(s5) ; ts.add(s6) ; for (Student s:ts) { System.out.println(s.getName()+"---"+s.getAge()); } } }
3, Map collection
1. Map collection:
The Map collection can have multiple values, but the key must be unique
2. Functions of Map collection
V put (k key, V value): adds a key value pair element
Note: if the key is added for the first time, the returned result is null
If the key is added repeatedly, the second time it is added, the value corresponding to the last added key will be returned
V remove(Object key): deletes the specified key and returns the value corresponding to the deleted key
boolean containsKey(Object key): whether the specified key is included
boolean containsValue(Object value): whether the specified value is included
Map traversal function
Set < k > keyset(): get the set of all keys in the current Map set
V get (Object key): get the value through the key
Mode 2:
Get key value pair object
Set< Map.Entry< K,V>>entrySet()
Get key / value from key value object
K getKey()
V geyValue()
public class MapDemo2 { public static void main(String[] args) { //Create a Map collection object Map<String,String> map = new HashMap<>() ; //Add element map.put("linghu chong","invincible eastern") ; map.put("Guo Yang","little dragon maiden") ; map.put("Chen Xuanfeng","Mei Chaofeng") ; map.put("Guo Jing","Huang Rong") ; // Set < k > keyset(): get the set of all keys in the current Map set Set<String> keySet = map.keySet(); //The first method is recommended //Enhanced for traversal for(String key: keySet){ //Get all key elements // V get(Object key): get the value through the key String value = map.get(key); System.out.println(key+"="+value); } System.out.println("--------------------------------------"); //Mode 2: //Set<Map.Entry<K,V>> entrySet() Set<Map.Entry<String, String>> entry = map.entrySet(); //Enhanced for: traversing key value pairs to get objects for(Map.Entry<String, String> en: entry){ //Get keys and values //K getKey() // V getValue() String key = en.getKey(); String value = en.getValue(); System.out.println(key+"="+value); } } }
3, HashMap
The put method of HashMap depends on hashCode() and equals methods. The key type must override the hashCode and equals methods of Object class to ensure that the key is unique!
4, TreeMap:
Red black tree structure - the keys of Map are sorted by conditions - the keys are user-defined
Construction method of TreeMap
public TreeMap(): sort keys naturally
Public treemap (comparator <? Super k > comparator): sort keys by comparator
4, Collection tool class Collections
Member method
public static <T extends Comparable<? Super T > > void sort (List < T > List): sort in natural ascending order (for List sets)
public static< T>void sort(List< T>)list,Comparator<? Super T > C): sort by comparator (for list set)
public static <T extends Object & Comparable<? Super T > > t max (collection <? Extensions T >: get the maximum value of the List in the current natural order
public static <T extends Object & Comparable<? Super T > > t min (collection <? Extensions T >: minimum
Public static void reverse (List <? > List): reverse the order of the List collection
Public static void shuffle (list <? > list): random displacement
5, Differences between Map and Collection collections
Collection: only one type of collection < E > can be stored
Map: there are two types: key type and value type. Map < K, V >
Different traversal methods:
Collection: 5 ways (traversal of List collection)
Map: two methods
Method 1: get the set of all K (the set of keys)
Get value by key
Method 2: get all key value pairs object map Entry< K,V>
Get all keys from the key value pair object
Get all values from the key value pair object
Internal connection:
TreeSet Collection - > collection - > indirectly uses the put method of TreeMap collection
HashSet collection indirectly uses the put method of HashMap
6, System class
The System class cannot be instantiated
Member variables:
public static final InputStream in: standard input stream
public static final PrintStream out: standard output stream
public static final PrintStream err: error output stream (print error information / some information that needs the user's attention: relevant logs)
System. Exit (0): the JVM exits. 0 means normal termination
public static void gc(): manually starting the garbage collector will recycle objects without more references in memory!
7, Abnormal
1. What is an exception
Exception: an exception is an error that occurs during the running of a Java program
2. Classification
error: very serious problem (not related to code)
Example: OOM Out Of Memory: memory overflow
Exception:
Compile time exception and runtime exception: problems occur during the running of the program (code writing is not rigorous)
As long as it is not a subclass of RuntimeException, it is a compile time exception
3. Exception handling
Mode 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) }
Mode 2
thows: Throw
3. The difference between compile time exceptions and run time exceptions
RuntimeException: runtime exception:
For the problems caused by the loose logical structure of general programmers, the caller can perform display processing (try... catch... / throws) or not display processing through logical statements
Compile time exception: the caller must display processing. If not, the compilation fails and the program cannot run
If it has been captured in the current method try...catch...,The caller processes out of order, But if an exception is thrown in a method,The caller must handle(capture/Throw throws)
4. The difference between throws and throw
Common ground: they are thrown
Different usage:
1) Different use positions
throws:
a) Throw exception on method declaration
b) The method name can be followed by multiple exception class names separated by commas
throw:
a) In a logical statement in the body of a method
b) Only the exception object, not the class name, can be followed
2) Does the caller handle different
Throws: the caller must perform display processing (try... catch/throws), or an error will be reported
throw: the caller does not need to perform display processing. Generally, it is processed in a logical statement
3) Is the abnormality positive
throws: on the method body, there may be a problem in the code executing a method (indicating a possibility of exception)
throw: this exception is bound to be executed when a piece of code is executed (indicating a certainty that an exception occurs)
4) Throws - > hand over the specific processing to the jvm - print the exception information on the console through the jvm, display the underlying source code, and display the current error message string
Throw --- > there is a problem with a piece of code in the program: just print the exception class name (jvm handling)
5, Throwable
public String getMessage() get detailed message string = = = public String getLocalizedMessage()
public String toString(): print a short description of the current exception information
6,finally
It cannot be used alone. It is used in combination with try... catch... finally. It is a standard format for handling exceptions
finally usage: features:
Release the relevant resources and the code will execute
Unless finally, the jvm exits
public class ExceptionDemo6 { public static void main(String[] args) { try{ String source = "2021-8-3" ; //Create a SimpleDateFormat object SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd ") ; //analysis Date date = sdf.parse(source) ; System.out.println(date); }catch (ParseException e){ //Use the functions in Throwabl //String result = e.getMessage();// Get message string // System.out.println(result); // String result = e.toString(); // System.out.println(result); e.printStackTrace(); System.exit(0); }finally{ //finally statement code must be executed! //Release resources System.out.println("Current system resources need to be released"); //JDBC (connection object / execution object Statement) //IO stream (create stream object, release stream object - system resources) //Inside the framework: Mybatis(JDBC encapsulation): execute the object SqlSession } } }
Interview questions
If an exception is caught in a method,
However, the method has a return value type. If a return statement appears in the catch statement, will the finally code be executed?
If it will be executed, before or after return
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,
Business code is rarely involved; Will be executed unless the jvm exits!
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 } }
7. Abnormal precautions
- When a subclass overrides a parent method, the subclass's method must throw the same exception or a subclass of the parent exception. (the father is bad, and the son can't be worse than his father)
- If the parent class throws multiple exceptions, when overriding the parent class, the child class can only throw the same exceptions or its subset, and the child class cannot throw exceptions that the parent class does not have
- If the overridden method does not throw an exception, the subclass method must not throw an exception. If an exception occurs in the subclass method, the subclass only throws an exception
Can try, can't throw
8, Binary search algorithm of advanced array search algorithm
The prerequisite array must be ordered. If the array itself is out of order, let's query the elements, sort them first, and then find them! (conditional requirements are sorted first and then queried
If there are no conditional requirements, you can only use the basic element lookup method: from beginning to end)
public class BinarySearch { public static void main(String[] args) { //Known array, static initialization int[] arr = {11,22,33,44,55} ; //Call the binary search method to query int index = binarySearch(arr, 22); System.out.println(index); int index2 = binarySearch(arr,66) ; System.out.println(index2); int index3 = binarySearch(arr,44) ; System.out.println(index3); System.out.println("-----------------------------------"); int index4 = Arrays.binarySearch(arr, 55); System.out.println(index4); int index5 = Arrays.binarySearch(arr, 66); System.out.println(index5); } //Return value int //Method parameters: array, query elements public static int binarySearch(int[] arr,int target){ //Prevent null pointer exceptions if(arr!=null){ //Define the minimum index of the array: int min = 0 ; //Define maximum index int max = arr.length -1 ; //Use loop while while(min<=max){ //Site index in calculation int mid = (min+max)/2 ; //If the element corresponding to the current location is smaller than the element to be found if(target < arr[mid]){ //Left half area: continue to half max = mid -1 ; }else if(target > arr[mid]){ //Right area: continue to fold in half min = mid + 1 ; }else{ //Yes return mid ; } } } //If it is not found after the loop ends, - 1 is returned return -1 ; } }
9, Thread
1. Process
An independent unit of a system unit that can be invoked
Understanding: computer ---- > open Task Manager ---- > client software ---- > application process
Computer startup - > service process (background process)
2. Thread
Belonging to the smallest unit of execution in a program (a task line in a process)
A process is composed of multiple threads. Multiple threads ----- > thread group
It is a single sequential control flow in a process and an execution path
If a process has only one execution path, it is called a single threaded program.
If a process has multiple execution paths, it is called a multithreaded program.
3. Meaning of multithreading
Characteristics of multithreading: randomness
Multiple threads preempt the execution right of the CPU
The role of multithreading is not to improve execution speed, but to improve the utilization of applications.
Multithreading gives us the illusion that multiple threads execute concurrently. Not really.
Because multiple threads share the resources of the same process (heap memory and method area), but the stack memory is independent. One thread has one stack. So they're still robbing
CPU resource execution. Only one thread can execute at a point in time. Moreover, it is not certain who gets it, so it causes the randomness of thread operation.
4. Implementation of thread 1
1) Declare a class as a subclass of Thread
2) This subclass should override the run method of the Thread class
3) You can then assign and start instances of subclasses
Start the thread with start() instead of run()
run() is just an ordinary method. There is no randomness in the execution of threads, and there will be no concurrent execution of two threads
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(); my2.start(); } }
5. Thread class
Construction method
Thread(String name): creates a thread class object and sets the name
Member method
public final String getName(): get thread name
public final void setName(String name): sets the name of the thread
6. 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 default priority
public final void setPriority(int newPriority): sets the priority of the thread
public final int getPriority(): get priority
Higher priority: the greater the preemption of CPU execution power
Low priority: the smaller the preemption of CPU execution power
Default priority: more random
public class ThreadDemo2 { public static void main(String[] args) {//User thread //Create an object of the MyThread2 class MyThread2 t1 = new MyThread2() ; MyThread2 t2 = new MyThread2() ; MyThread2 t3 = new MyThread2() ; // public final void setName(String name): sets the thread name t1.setName("I love you!") ; t2.setName("marry") ; t3.setName("She 123"); t1.setPriority(10); //Maximum priority t2.setPriority(1);//Minimum priority int num1 = t1.getPriority(); int num2 = t2.getPriority(); int num3 = t3.getPriority(); System.out.println(num1+"---"+num2+"---"+num3); //Start thread t1.start(); t2.start(); t3.start(); } }
7,join,yield
Join(): --- > join (0) - -- > synchronization method, which can ensure thread safety
Wait for the thread to terminate, and then other threads continue to execute concurrently
yield(): pause the currently executing thread and execute the other thread!
8. Status of the thread
Thread class internal enumeration class
public enum State{
NEW, NEW (not implemented)
RUNNABLE, running status (possible blocking)
BLOCKED, thread blocking status (wait,sleep...)
Waiting, wait (the bottom layer calls the wait() method)
TIMED_ Waiting, timeout waiting (directly call wait(long timeout))
TERMINATED; Thread termination dead state (thread execution completed)
}
9. Implementation of thread 2
1) The custom class implements the Runnable interface
2) Override the run method of the Runnable interface
3) In the main user thread, you can assign an instance of a class (create an instance of a class)
4) Create the current class object, then create the Thread class object, and pass the current class object as a parameter
Current class - resource sharing class“
Thread(Runnable target,String name)
5) Start threads separately
//Resource class 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); } } }
//Thread implementation class 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 San") ; Thread t2 = new Thread(my,"Li Si") ; //Start threads separately t1.start(); t2.start(); } }
10. Static proxy
Thread class: it is the proxy class
Customized myrunnable implementation - > real role
Static proxy:
Real role: only focus on your own things (your own business functions)
Agent class: help real roles accomplish some things (enhance the business functions of real roles)
Both proxy classes and real roles need to implement the same interface
Dynamic agent
In the process of program execution, the agent role is generated through this reflection
jdk dynamic proxy: an interface based proxy (reflection)
cglib: a subclass based proxy (Spring)
11. Thread safety issues
Criteria for checking thread safety issues
1) Is it a multithreaded environment
2) Is there a resource sharing
3) Whether there are multiple statements to operate on shared data
solve:
Java provides a synchronization mechanism: synchronize code blocks to wrap multiple statements around shared data
Synchronized (lock object){
Wrap multiple statements around shared data
}
Lock object: the same lock object must be used by multiple threads instead of their own lock objects. The lock object can be any java type class object
12. Synchronization
Premise of synchronization
Multiple threads
Multiple threads use the same lock object
Benefits of synchronization
The emergence of synchronization solves the security problem of multithreading.
Disadvantages of synchronization
When there are a large number of threads, each thread will judge the lock on synchronization, which is very resource-consuming and will virtually reduce the running efficiency of the program.
Sync code block:
Synchronized (lock object){
}
Synchronization method:
public /private syncrhonized return value type method name (formal parameter list){
...
}
13. Deadlock problem
Thread safety problem: it can be solved through synchronization methods or synchronized code blocks, but deadlock may occur during execution
(use the synchronization mechanism to solve thread safety) there is a situation of waiting for each other between threads!
Solution
Communication between multiple threads: the same resource class must be used, not each thread using its own resource class object
Using the idea of producer and consumer model,
Prerequisite: the producer thread and the consumer thread must operate on the same resource class object
Deadlock code
// Class of lock object public class MyMonitor { //Two lock objects are provided public static final Object objA = new Object() ; public static final Object objB = new Object() ; }
//Resource class public class DieLock implements Runnable { private boolean flag ;//Tag value public DieLock(boolean flag){ this.flag = flag ; } @Override public void run() { //Judge tag value //t1 ---->DieLock(true) //t2 ---->DieLock(false) if(flag){ //t1 synchronized (MyMonitor.objA){ System.out.println("if ObjeA");//"if objA" synchronized (MyMonitor.objB){ System.out.println("if objB");// "if objB" } } }else{ //t2 synchronized (MyMonitor.objB){ System.out.println("else ObjB"); //else objB synchronized (MyMonitor.objA){ System.out.println("else objA"); //"else objA" } } } } }
public class DieLockDemo { public static void main(String[] args) { //Create resource class object DieLock d1 = new DieLock(true) ; DieLock d2 = new DieLock(false) ; //Create objects in Thread Thread t1 = new Thread(d1) ; Thread t2 = new Thread(d2) ; //Start separately t1.start(); t2.start(); } }
14. Use the producer and consumer mindset - resolve thread deadlocks
//Steamed stuffed bun public class StuffBun { //Member variables are not privatized private String name ;//Type of steamed stuffed bun (meat steamed stuffed bun, vegetable steamed stuffed bun) private String bunType ;//Big steamed stuffed bun / small steamed stuffed bun //Definition flag: indicates whether there is package sub data private boolean flag ; //The default is false and there is no data //Method for assigning value to package data public synchronized void set(String name,String bunType){ //The lock object is this: a non static synchronization method //If the current producer has no statements, it needs to wait for data generation if(this.flag){ //The lock object calls wait to send that message try { this.wait();//Release lock object } catch (InterruptedException e) { e.printStackTrace(); } } //assignment this.name = name ; this.bunType = bunType ; //If you have data now //Change signal this.flag = true ;//There are data classes //Notify (wake up) the consumer thread to use the data quickly this.notify(); //Wake up the other thread } //Providing method: obtain the data of steamed stuffed bun public synchronized void get(){ //Non static synchronization method: lock object this //If there is package data in the current consumption resource class, wait for the consumption data to be used first if(!this.flag){ //Waiting for data to be used up try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(this.name+"---"+this.bunType); //Change signal value //If the steamed stuffed bun is consumed this.flag = false ; //Wake up the other thread (producer resource class, don't wait, generate data) this.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() { //Produce steamed stuffed bun /* StuffBun stu = new StuffBun() ; stu.name = "Meat bun "; stu.bunType = "Large type ";*/ //Continuously generate data while(true){ if(x % 2 == 0){//t1 //stu.name = "meat buns"; //stu.bunType = "big steamed stuffed bun"; stu.set("steamed meat bun","Big stuffed bun"); }else{ //stu.name = "steamed stuffed bun"; //stu.bunType = "small steamed stuffed bun"; stu.set("vegetable bun","Steamed stuffed bun"); } x ++ ; } } }
//Consumer resources public class GetBun implements Runnable { //Declare the variable stb 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){ stu.get();//Get package data } } }
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(); } }
15,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 seize 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
Cinema ticket problem
import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * Resource class - needs to be shared by multiple threads */ 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(); } }
16. Thread group ThreadGroup
A thread group represents a group of threads
All threads can be added to a group to facilitate management,
After the thread is started and terminated, the thread object will not be reused in memory
Thread: ->
public final ThreadGroup getThreadGroup() {/ / get thread group
return group;
}
ThreadGroup:
public final String getName() {: get the default thread group name
return name;
}
Construction method:
public ThreadGroup(String name) {}
public class MyThread implements Runnable { @Override public void run() { for(int x = 0 ;x < 100 ; x ++){ System.out.println(Thread.currentThread().getName()+":"+x); } } }
public class ThreadGroupDemo { public static void main(String[] args) { //The jvm calls the main method // method1(); method2() ; } //Set a new thread group name private static void method2() { //Create a thread group object -- set the thread group name at the same time ThreadGroup tg = new ThreadGroup("myMain") ; //Create two thread objects MyThread my = new MyThread() ; Thread t1 = new Thread(tg,my) ; Thread t2 = new Thread(tg,my) ; //Get the thread group object and the thread group name at the same time String name1 = t1.getThreadGroup().getName(); String name2 = t2.getThreadGroup().getName(); System.out.println(name1+"---"+name2); } private static void method1() { //Create two threads MyThread my = new MyThread() ; Thread t1 = new Thread(my) ; Thread t2 = new Thread(my) ; ThreadGroup tg1 = t1.getThreadGroup(); ThreadGroup tg2 = t2.getThreadGroup(); String name1 = tg1.getName(); String name2 = tg2.getName(); System.out.println(name1+"---"+name2); //The default thread group name is main } }
17. Thread pool
Thread pool belongs to the "pooling" technology -- -- > similar to database connection pool (DBCP, C3PO, Druid (born for monitoring))
characteristic:
Create a fixed number of reusable threads in memory. The current thread terminates after execution and will not be recycled. Try again
Return to the thread pool and wait for the next utilization!
Disadvantages: high maintenance cost
public class MyRunnable implements Runnable { @Override public void run() { for(int x = 0 ; x < 100 ; x ++){ System.out.println(Thread.currentThread().getName()+":"+x); } } }
import java.util.TreeMap; 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; } }
import java.util.concurrent.Callable; 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); //Commit asynchronous method //MyRunnable: print the data between the value of x and 0-99. No result needs to be returned // threadPool.submit(new MyRunnable()) ; // threadPool.submit(new MyRunnable()) ; // <T> Future<T> submit(Callable<T> task) //Callable: submit asynchronous calculation - the callable call needs to be rewritten to calculate the result; If there is no result, you do not need to return it directly in the call threadPool.submit(new MyCallable()) ; threadPool.submit(new MyCallable()) ; //void shutdown() closes the thread pool threadPool.shutdown(); } }