catalogue
1. Inherit the Thread class and override the run () method
2. Implement the Runnable interface and rewrite the run method
5. User thread and daemon thread
1. Thread synchronization mechanism
thread
Process: refers to a running program. A process is an execution process of a program (a running program)
Threads: threads are created by processes. A process can have multiple threads
①. Single thread: only one thread is executed at the same time
②. Multithreading: execute multiple threads at the same time (download songs and videos at the same time)
③. Concurrency: multiple threads execute alternately at the same time (when you call while driving, the brain is actually switching)
④. Parallel: multiple threads execute simultaneously at the same time (playing with the mobile phone while going to the bathroom)
I Thread usage
1. Inherit the Thread class and override the run () method
A class inherits the} Thread class, which can be used as a Thread and override the run () method
new App().new A().start(); for (int i = 5; i < 10; i++) { System.out.print("11111" + "\t"); Thread.sleep(500); } } class A extends Thread { @Override public void run() { for (int i = 0; i < 5; i++) { System.out.println("22222"); try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
Output:
2. Implement the Runnable interface and rewrite the run method
java is single inheritance. In some cases, a class may have inherited a parent class. At this time, it is obviously impossible to inherit the Thread class
After the class implementing the Runnable interface is instantiated, there is no start () method, and a Thread object needs to be created,
Then pass in the class that implements the Runnable interface as a parameter
Thread t = new Thread(new App().new A()); t.start(); for (int i = 0; i < 5; i++) { System.out.print("11111" + "\t"); Thread.sleep(500); } } class A implements Runnable { @Override public void run() { for (int i = 0; i < 5; i++) { System.out.println("22222"); try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
Output:
II Common methods of thread
1.setName() set thread name |
2.getName() returns the thread name |
3.setPriority() changes the priority of the thread (in the range of 1-10) ①.MIN_PRIORITY = 1 ②.NORM_PRIORITY = 5 ③.MAX_PRIORITY = 10 |
4.getPriority() gets the priority of the thread |
5.run() calls the run() method of the thread object |
6.start() is when the thread starts executing, and start0() is called |
7.slee() sleeps the specified thread |
8.interrupt() interrupt thread (thread in sleep) |
9.Thread.currentThread() main thread |
10.yield() comity thread (time is uncertain and comity may not succeed) |
11.join() thread queue jumping |
1. 1--4
A a = new App().new A(); // 1.setName() set thread name a.setName("Zhang San"); // 2.getName() returns the thread name System.out.println(a.getName()); // 3.setPriority() change the priority of the thread a.setPriority(Thread.MIN_PRIORITY); // 4.getPriority() gets the priority of the thread System.out.println(a.getPriority());
Output:
2. 5
Calling the run () method does not implement multithreading, it can only output in order
A a1 = new App().new A(); // 5.run() calls the run() method of the thread object a1.run(); System.out.print(Thread.currentThread().getName() + "\t"); System.out.println("1000");
Output:
3. 6--9
A a1 = new App().new A(); // 6.start() is when the thread starts executing, and start0() is called a1.start(); for (int i = 0; i < 5; i++) { // 9.Thread.currentThread() main thread System.out.print(Thread.currentThread() + "\t"); System.out.println(i); // 7.slee() sleeps the specified thread Thread.sleep(1000); } // 8.interrupt() interrupt thread (thread in sleep) a1.interrupt();//Wake up } class A extends Thread { @Override public void run() { for (int i = 0; i < 5; i++) { System.out.print(getName() + "\t"); System.out.println(i); if (i == 2) {//Sleep for 20 seconds try { Thread.sleep(20000); } catch (InterruptedException e) { System.out.println("aaaaa"); } } } } }
Output:
4.10--11
Start() called start0()
A a1 = new App().new A(); a1.start(); for (int i = 0; i < 5; i++) { System.out.print(Thread.currentThread().getName() + "\t"); System.out.println(i); if (i == 3) { // 11.join() thread queue jumping a1.join(); } } } class A extends Thread { @Override public void run() { for (int i = 0; i < 5; i++) { System.out.print(getName() + "\t"); System.out.println(i); if (i == 1) { // 10.yield() comity thread (time is uncertain and comity may not succeed) Thread.yield(); } } } }
Output:
5. User thread and daemon thread
setDaemon() sets the daemon thread
①. User thread: also called worker thread, when the task of the thread is completed or the notification ends
②. Daemon thread: it serves for worker threads. When all worker threads end, the daemon thread ends automatically (the garbage collection mechanism is daemon thread)
A a1 = new App().new A(); a1.setDaemon(true); a1.start(); for (int i = 0; i < 2; i++) { System.out.print(Thread.currentThread().getName() + "\t"); System.out.println(i); } } class A extends Thread { @Override public void run() { for (int i = 0; i < 5; i++) { System.out.print(getName() + "\t"); System.out.println(i); } } }
Output:
III Status of the thread
1.new: when the thread is not started. Creating a thread object does not start before start()
2.RUNNABLE: when running. After running the strat method
3.BLOCKED: blocking status, waiting for entering the lock of the synchronization code block
4.WAITING: waiting status. After executing wait(), join(), park()
5.TIMED_WAITING: timeout WAITING state. Adding sleep() to the WAITING method
6.TERMINATED: terminated status (when the thread ends). The thread is completed, interrupted and aborted
Sketch Map:
IV Synchronized
1. Thread synchronization mechanism
In multithreading, some sensitive data is not allowed to be accessed by multiple threads at the same time. At this time, synchronization is needed to ensure that data can only be accessed by one thread at a time.
When a thread is operating on memory, other threads cannot operate on the memory address until the thread completes the operation
2. Mutex
①. To ensure the integrity of shared data
②. When an object is decorated with {Synchronized, the surface can only be accessed by one thread at a time
③. Program execution efficiency will become low
④. The lock of the synchronization method (non static) is this by default, and can also be other objects
⑤. The lock of the synchronization method (static) is the current class itself, class. Class
Synchronization method
A a1 = new App().new A(); new Thread(a1).start(); new Thread(a1).start(); new Thread(a1).start(); } class A implements Runnable { private int j = 10; boolean q = true; public synchronized void a() { if (j <= 0) { q = false; return; } System.out.print(Thread.currentThread().getName() + "\t"); System.out.println(j--); } @Override public void run() { while (q) { a(); } } }
Output:
Synchronous code block
A a1 = new A(); new Thread(a1).start(); new Thread(a1).start(); new Thread(a1).start(); } } class A implements Runnable { static private int j = 10; static boolean q = true; public static void a() { synchronized (A.class) { if (j <= 0) { q = false; return; } System.out.print(Thread.currentThread().getName() + "\t"); System.out.println(j--); try { Thread.sleep(50); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } @Override public void run() { while (q) { a(); } } }
Output:
3. Release the lock
Release of lock
①. Synchronization method or synchronization code block of the current thread: end of execution
②. Synchronization method or synchronization code block of the current thread: break and return encountered
③. Synchronization method or synchronization code block of the current thread: an unhandled Error or Exception occurred, resulting in abnormal end
④. Synchronization method or synchronization code block of the current thread: wait() is executed, and the thread is suspended
The lock will not be released
①. When the thread executes the synchronization method or synchronization code block: the program calls the sleep() and yield() methods to pause the current thread
②. When a thread synchronizes a code block, the thread hangs when another thread calls the thread's suspend () method
4. Deadlock
When a thread waits for a resource and the resource is occupied by another thread, it will cause a deadlock
new Thread(new A(true)).start(); new Thread(new A(false)).start(); } } class A implements Runnable { static Object o1 = new Object();//Static members are shared static Object o2 = new Object(); boolean b; public A(boolean b) { this.b = b; } @Override public void run() { if (b) { synchronized (o1) { System.out.println("o1"); synchronized (o2) { System.out.println("o2"); } } } else { synchronized (o2) { System.out.println("o2"); synchronized (o1) { System.out.println("o1"); } } } } }
It's stuck (you give it to me first, no, you give it to me first)
Output: