1. Introduction to Threads
(1) Processes: Running applications
(2) Thread: Execution path of process, execution unit
2. Two Implementations of Threads
(1) Inheriting the Thread class;
public class MyThread extends Thread{
//1. Inheriting the Thread class
//2. Rewrite the run method, rewrite the code in the run method, and when we start the thread, our thread will execute the code in the run method.
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(i);
}
}
}
(2) Implementing Runnable Interface
public class MyThread implements Runnable{
@Override
public void run() {
//After starting the thread object, the code to be executed
for (int i = 0; i < 10; i++) {
System.out.println(i);
}
}
}
What is the difference between start() and run()?
start():1. Open the thread 2. Execute the code in the run() method
run(): Executes code that is executed within a thread and does not open the thread
Common methods in threading:
Thread.sleep(long millis) ;//Sleep (pause) the currently executing thread for a specified number of milliseconds.
setName(String name);//Change the thread name
getName();//Returns the name of the thread
setPriority(int newPriority);//Change the priority of threads, default value is 5, range from 1 to 10.
3. Multithread security issues
1. Multithread security issues
(1) Is it a multi-threaded environment?
(2) whether there is shared data;
(3) Whether there are multiple statements to manipulate and share data.
2. How to solve the problem of multithreading security:
Synchronized Code Block and Lock Use
Synchronized (object){ // Code that needs to be synchronized. }
Notice three points
First, the object: any object, the object will become a lock, as long as the thread into the lock;
Second, code that needs to be synchronized: code that has thread security problems;
Thirdly, the requirement of synchronization code block for lock: multiple threads need to share a lock.
(2) Lock object problem:
A: Synchronize code blocks (define an abstract class, which specifically defines a lock): any object.
B: Synchronization method (only applicable to the implementation of Runnable interface): The synchronized keyword is added to the method, and the lock of the synchronization method is this.
For example: multi-threaded ticketing problem.
private synchronized void sellTicket() {
//Synchronized code
if (ticket>0) {
//Considering that in real life, we need to add a certain delay to each thread to simulate this effect.
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"Sales of the _____________"+ticket--+"Zhang ticket");
}
}
C: Static synchronization method: Its lock is this kind of bytecode file object: class name. class. For example: synchronized (MyThread.class)
private static synchronized void sellTicket() {
//Synchronized code
if (ticket>0) {
//Considering that in real life, we need to add a certain delay to each thread to simulate this effect.
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"Sales of the _____________"+ticket--+"Zhang ticket");
}
Using multithreading in the way of anonymous internal classes
1. Inherit the Thread class:
new Thread() {
public void run() {
...
}
}.start();
2. Implement Runnable interface:
new Thread(new Runnable(){
public void run() {
...
}
}).start();
Lock lock of JDK5
1.Lock implementations provide a wider range of locking operations than can be obtained using synchronized methods and statements.
static Lock lock = new ReentrantLock();
lock.lock();//Lock
lock.unlock();//Release lock
2.void lock() gets the lock. If the lock is not available, the current thread will be disabled for thread scheduling purposes and will remain dormant until the lock is acquired.
3.void unlock() releases the lock.
4. Without block-structured locks, the automatic release function of locks will be lost when synchronized methods and statements are used. To ensure that the lock we created will be released, we use the following code to improve it:
Lock l = ...;
l.lock();
try {
// access the resource protected by this lock
} finally {
l.unlock();
}
5. Deadlock problem: Synchronized nesting, a lock inside the lock, will appear deadlock problem, so in the process of writing code in the future as far as possible to avoid synchronized nesting.
Thread Waiting and Waking Mechanism
Case: waitThread, Notify Thread, MyLock, Test.
Get the lock object:
package com.edu_01;
public abstract class MyLock {
public static final Object obj = new Object();
}
Waiting mechanism:
public class WaitThread extends Thread{
@Override
public void run() {
synchronized (MyLock.obj) {
//Keep the waiting thread in wait state
try {
MyLock.obj.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("I was awakened.");
}
}
Wake-up mechanism:
public class NotifyThread extends Thread{
@Override
public void run() {
synchronized (MyLock.obj) {
//Wake up waiting threads
MyLock.obj.notify();//Wake up the waiting thread. Wake up the lock object of the waiting thread must be the same as the lock object of the waiting thread.
}
}
}
Test class:
public class Test {
public static void main(String[] args) {
//Create waiting threads to keep waiting threads in a waiting state
WaitThread wt = new WaitThread();
wt.start();
//Wake up the waiting thread after 5 seconds of sleep
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Create wake-up Thread objects
NotifyThread nt = new NotifyThread();
nt.start();
}
}
What is the difference between wait() and sleep()?
wait(): In the process of thread waiting, the program will not continue to execute, while waiting, it will release the lock in hand.
sleep(): During the process of thread hibernation, the lock in hand will not be released.
Wake up the waiting thread. Wake up the lock object of the waiting thread must be the same as the lock object of the waiting thread.