Event address: CSDN 21 Day Learning Challenge
1. What is a thread
To understand what a thread is, you must first understand a process
Process: A simple understanding is the running program
Thread: A thread is the smallest unit in a process, and there is at least one thread in a process
There is no concept of a process in the CPU, it only has the concept of a thread, and the CPU will quickly switch threads to execute code
Thread conference CPU is a resource, and everyone will preempt the CPU. Whoever preempts it will run whose thread
Note: The CPU can only perform one thread in the same time slice
Time slice: refers to a very microscopic time
2. The use of threads
Thread is a thread class provided to us by java. As long as it inherits Thread, our custom class is a thread class
need :
Defines a game class: his core method is to print "playing the game";
One more music category: his core method is to print "White Dragon Horse..."
There is a core method run() in the thread class; we need to override it
Then after we instantiate the thread object, we need to activate the thread object through the start() method in the Thread class so that it has the right to preempt the thread
code show as below
public class Thread_Text_1 { static class GameThread extends Thread{ @Override public void run() { for (int i = 0; i <100; i++) { System.out.println("---->game in progress"+i); } } } static class MusicThread extends Thread{ @Override public void run() { for (int i = 0; i <100; i++) { System.out.println("---->music playing"+i); } } } public static void main(String[] args) { GameThread gameThread=new GameThread();// Create a thread object gameThread.start();// Activate the thread and let the object get the execution right of the CPU MusicThread musicThread=new MusicThread(); musicThread.start(); for (int i = 0; i <100; i++) { System.out.println("---->main"); } } }
There are a total of three threads in the code
1. Main method Main Thread
2,Game Thread
3,Music Thread
3. Notes on thread usage
In future code writing, the logic code can be written directly in the Run method in the Thread class
But you can't call the Run() method directly, and calling the Run() method directly will not open a thread
The start() method needs to be called to activate the thread, so that the current thread is in an active state
When the total thread is activated and started, it has nothing to do with the main thread, and the two threads will not have any connection
4. Thread use case – train ticket sales
need
The current train station has a total of 200 train tickets
Then, three ticket windows were opened to sell train tickets at the same time.
code show as below
public class Thread_Text_2 { static class PiaoThread extends Thread{ static int sum=100; String ThreadName; public PiaoThread(String threadName){ ThreadName=threadName; } @Override public void run() { while (sum>0){ System.out.println(ThreadName+"Tickets are being issued, ticket number is"+sum); sum--; } } } public static void main(String[] args) { // instantiate the thread object PiaoThread piaoThread1=new PiaoThread("window one"); PiaoThread piaoThread2=new PiaoThread("window two"); PiaoThread piaoThread3=new PiaoThread("window three"); // activate thread piaoThread1.start(); piaoThread2.start(); piaoThread3.start(); } }
The code works theoretically. But there will be a problem of heavy tickets, which involves thread safety
Tickets are being issued at window 1, and the ticket number is 100
Tickets are being issued at window 3, and the ticket number is 100
Tickets are being issued at window 2, and the ticket number is 100
5. Thread safety issues
When thread A preempts the execution right of the CPU and the conditions are met, the ticket number is 100.
At this time, the CPU is preempted by thread B before the sum- operation is performed, so the ticket number that is still issued is still 100.
The information error phenomenon that occurs when multiple threads preempt the CPU, which is a thread safety problem
Thread safety problem Solution: lock
6. Modify the thread name
currentThread(): This method is used to return a reference to the currently executing thread object
getName(): This method is used to return the name of the current thread
There are two ways to modify the thread name
1. Name the thread through the constructor
static class PiaoThread extends Thread{ static int sum=100; public PiaoThread(String threadName){ super(threadName); } }
2. Modify the thread name through the setName() method
static class PiaoThread extends Thread{ static int sum=100; public PiaoThread(String threadName){ setName(threadName); } }
7. Thread sleep
The sleep() method is provided in Thread to make the thread sleep for a specified time
try { sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }
8. Two ways to implement threads
The first is to inherit Thread through a class
Just extend Thread directly
The second is to implement Runnable through a custom class
new Thread (the implementation class of Rannable) can
Because Thread has only run() method
If you want the thread to be active and have CPU control, it must be implemented through Rannaable
code show as below
public class Thread_Text_3{ public static void main(String[] args) { Thread_Runnable thread_runnable1=new Thread_Runnable(); Thread thread1=new Thread(thread_runnable1); thread1.start(); Thread_Runnable thread_runnable2=new Thread_Runnable(); Thread thread2=new Thread(thread_runnable2); thread2.start(); Thread_Runnable thread_runnable3=new Thread_Runnable(); Thread thread3=new Thread(thread_runnable3); thread3.start(); } static class Thread_Runnable implements Runnable{ static int sum=100; @Override public void run() { while (sum>0){ System.out.println(Thread.currentThread().getName()+"sell"+sum); sum--; } } } }
9. Solve thread safety issues
There are three ways to solve the problem of thread safety
1, synchronized synchronization code block
2. Synchronization method
3. Use Lock
The essence of these three methods is to lock the code
Notice :
To lock the code, you must ensure that the code that needs to be locked uses the same lock
How does a synchronized code block ensure that the locked code is the same lock?
Just use bytecode objects a unique bytecode object exists for each class
class name.class: you can
1. Code synchronization block
@Override public void run() { while (sum>0){ synchronized (Thread_Runnable.class){ if (sum>0){ System.out.println(Thread.currentThread().getName()+"sell"+sum+""); sum--; } } } }
2. Synchronization method
Synchronous methods only need to encapsulate the code to be executed into a method
Just add the synchronized declaration before the method void declaration
Note that if you implement Thread using inheritance then you cannot use synchronized methods
3. Lock
This method is more extensive and flexible than synchronized
We create a lock object by instantiating the Lock object
code show as below
public class Thread_Text_4 { static class Thread_ extends Thread{ int sum=100; static Lock lock =new ReentrantLock(); // Create lock object @Override public void run() { // locked while (sum>0){ lock.lock(); try { System.out.println(Thread.currentThread().getName() + "Tickets are being issued, ticket number is" + sum + " " + Thread.currentThread().getName() + " " ); sum--; }finally { lock.unlock(); } } } } public static void main(String[] args) { Thread_ thread1=new Thread_(); Thread_ thread2=new Thread_(); Thread_ thread3=new Thread_(); thread1.start(); thread2.start(); thread3.start(); } }
Notice:
The Lock instance object must ensure that the participating threads are all using the same lock, so you need to add Static
Then lock through the Lock.lock() method
Release the lock through the Lock.unlock() method
Use these two methods must cooperate with Try...finally to ensure that resources can be released even if the code reports an error