Main thread: The thread that executes the main method is called the main thread
Single-threaded program: The program runs sequentially from top to bottom starting from mani
The program starts running from the main method. When the JVM runs the main method, it will find the operating system.
Open up an execution path to the cpu. The cpu can execute the main method through this path.
This path has a The name is the main thread
Create thread method 1: Inherit the Thread class
Implementation steps:
1. Create a subclass of the Thread class
2. Rewrite The run method in the Thread class sets the task of the thread
3. Create a subclass object of the Thread class
4. Call the start method in the Thread class to start a new thread, and execute the run method
to start the thread Start execution; the Java virtual machine calls the run method of the thread.
The result is that two threads run concurrently; the current thread (the main thread) and the other thread (the thread executing the run method).
It is illegal to start a thread multiple times. Especially when a thread has finished executing, it cannot be restarted.
The printed results appear random:
Start two threads and select the right for the CPU
Whoever you like will be executed, so random results appear
1 public class MyThread extends Thread{ 2 /* 3 * 2.重写Thread类中的run方法,设置线程的任务 4 * 开启这个线程要干什么事情 5 */ 6 @Override 7 public void run() { 8 for (int i = 0; i < 50; i++) { 9 System.out.println("run..."+i);10 }11 }12 }13 public static void main(String[] args) {14 //3.创建Thread类的子类对象15 MyThread mt = new MyThread();16 //mt.run();//不会开启线程,还是单线程程序17 //4.调用Thread类中的start方法开启一个新的线程,执行run方法18 mt.start();19 20 new MyThread().start();21 22 for (int i = 0; i < 50; i++) {23 System.out.println("main..."+i);24 }25 }
The name of the thread:
Main thread:"main"
The names of other opened threads:"Thread-0","Thread-1"....
Get the name of the thread
1. The method getName in the Thread class
String getName() returns the name of the thread.
2. Static method in the Thread class to obtain the currently executing thread
static Thread currentThread() returns a reference to the currently executing thread object.
Set the name of the thread:
1. Method setName(String name) in the Thread class
void setName(String name) changes the thread name so that it is the same as the parameter name.
2. Add a constructor with parameters to the subclass, call the constructor with parameters of the parent class Thread class, pass the name of the thread, and let the parent class name the thread (let the father name the son)
Thread(String name ) allocates a new Thread object.
Create thread mode—implement Runnable interface
Implementation steps:
1. Create an implementation class of Runnable interface
2. Rewrite the run method in Runnable interface, Set thread tasks
3. Create an implementation class object of the Runnable interface
4. Create a Thread class object, and pass in the implementation class of the Runnable interface in the constructor
Thread(Runnable target) allocates a new Thread object.
5. Call the start method in the Thread class to start the thread to execute the run method
Benefits of implementing Runnable
1. It prevents a class from inheriting the Thread class from inheriting other classes ( Limitations of single inheritance)
2. Decouple setting thread tasks and starting threads, enhancing scalability
The role of the implementation class: setting thread tasks
The role of the Thread class: starting threads
Benefits: Passing different implementation classes, the implementation class overrides the method in different ways, and you can call different methods
Use anonymous internal classes of threads
Anonymous: no name
Internal Class: a class written inside other classes (member position: member inner class, local position (in method): local inner class)
Format of anonymous inner class:
new parent class/interface () {
Override methods in parent class/interface;
};
Multi-threaded parent class:
Thread
Runnable
1 new Thread(){2 //重写run方法,设置线程任务3 @Override4 public void run() {5 for (int i = 0; i < 20; i++) {6 System.out.println(Thread.currentThread().getName()+":"+i);7 }8 }9 }
The above pile of code is a process of creating a subclass and overriding the parent class method
Equivalent to: new MyThread().start();
There is a thread safety problem in the program: duplicates are sold Tickets and non-existent tickets
Solution:
The first way: you can use synchronized code block
synchronized (lock object){
Code that generates security issues;
Code that accesses shared data;
}
Note:
It is necessary to ensure that multiple threads use the same lock object
//Create a lock object at the member position (Guaranteed to be unique)
1 Object obj = new Object(); 2 3 @Override 4 public void run() { 5 //让卖票重复执行 6 while(true){ 7 8 * 同步代码块 9 * 程序会频繁的判断锁,获取锁,释放锁,所以会降低速度10 11 synchronized (obj) {12 if(ticket>0){13 //为了提高安全问题的概率,让程序睡眠14 try {15 Thread.sleep(10);16 } catch (InterruptedException e) {17 e.printStackTrace();18 }19 //卖票ticket--20 System.out.println(Thread.currentThread().getName()+"...卖第"+ticket--+"张票");21 }22 }23 }24 }
The program has a thread safety problem: duplicate tickets and non-existent tickets are sold
Solution:
The second way :Synchronization method
Usage steps:
1. Extract the code that may cause security problems into a method
2. Add a keyword synchronized
to the method Modifier synchronized Return value type Method name (parameter) {
Code that may have security issues;
Code that accesses shared data;
}
What is the lock object used by the synchronization method?
Used It is this class object new RunnableImpl()-->Call this
Static synchronization method, what lock object is used?
What is used is the class attribute (reflection) of this class object
RunnableImpl .class
1 *@Override 2 public void run() { 3 //让卖票重复执行 4 while(true){ 5 payTicket2(); 6 } 7 } 8 9 10 * 静态的同步方法11 12 public static synchronized void payTicket2(){13 synchronized (RunnableImpl.class) {14 if(ticket>0){15 //为了提高安全问题的概率,让程序睡眠16 try {17 Thread.sleep(10);18 } catch (InterruptedException e) {19 e.printStackTrace();20 }21 //卖票ticket--22 System.out.println(Thread.currentThread().getName()+"...卖第"+ticket--+"张票");23 }24 }25 }26 27 28 29 * 抽取出一个同步方法30 * 快捷键:alt+shift+m31 32 public ynchronized void payTicket1() {33 synchronized (this) {34 //System.out.println(this);//cn.itcsat.demo10.RunnableImpl@6706435 if(ticket>0){36 //为了提高安全问题的概率,让程序睡眠37 try {38 Thread.sleep(10);39 } catch (InterruptedException e) {40 e.printStackTrace();41 }42 //卖票ticket--43 System.out.println(Thread.currentThread().getName()+"...卖第"+ticket--+"张票");44 }45 }46 }
程序出现了线程安全问题:卖了重复的票和不存在的票
*
* 解决方案:
* 第三种方式:使用Lock接口,JDK1.5之后出现的
*
* java.util.concurrent.locks.Lock接口
* 方法:
* void lock() 获取锁。
* void unlock() 释放锁。
* 接口的实现类:ReentrantLock
*
* 实现步骤:
* 1.在成员位置创建一个Lock接口的实现类对象ReentrantLock
* 2.在可能出现线程安全问题的代码前,调用lock方法获取锁
* 3.在可能出现线程安全问题的代码后,调用unlock方法释放锁
*
*1.在成员位置创建一个Lock接口的实现类对象ReentrantLock
Lock l = new ReentrantLock();
1 @Override 2 public void run() { 3 //让卖票重复执行 4 while(true){ 5 //2.在可能出现线程安全问题的代码前,调用lock方法获取锁 6 l.lock(); 7 if(ticket>0){ 8 //为了提高安全问题的概率,让程序睡眠 9 try {10 Thread.sleep(10);11 //卖票ticket--12 System.out.println(Thread.currentThread().getName()+"...卖第"+ticket--+"张票");13 } catch (InterruptedException e) {14 e.printStackTrace();15 }finally {16 //3.在可能出现线程安全问题的代码后,调用unlock方法释放锁17 l.unlock(); 18 }19 }20 }
The above is the detailed content of Thread, thread creation example tutorial. For more information, please follow other related articles on the PHP Chinese website!