search
HomeJavajavaTutorialJava concurrent programming: How to use the Thread class?
Java concurrent programming: How to use the Thread class?Jun 23, 2017 am 09:16 AM
javathreaduseconcurrentprogramming

Java Concurrent Programming: Use of Thread Class
 
The following is the table of contents outline of this article:
 1. Thread status
 II.Context Switch
3. Methods in the Thread class
 
Reprinted from:
 

1. Thread status

 Threads go through several states from creation to final death. Generally speaking, threads include the following states: creation (new), ready (runnable), running (running), blocked (blocked), time waiting, waiting, and death (dead).
 
The picture below describes the state of a thread from creation to death:

In some tutorials, blocked, waiting, and time waiting are collectively referred to as blocking states. This is also possible, but here I want to link the state of the thread with the method call in Java, so the two states of waiting and time waiting are separate from.

2. Context switching

 For a single-core CPU (for a multi-core CPU, this is understood as one core), the CPU can only run one thread at a time. Switching to running another thread while running one thread is called thread context switching (the same is true for processes).
 

Three.Methods in the Thread class

By looking at the source code of the java.lang.Thread class we can see:
 

The Thread class implements the Runnable interface. In the Thread class, there are some key attributes. For example, name is the name of the Thread, which can be specified through the parameters in the constructor of the Thread class. Thread name, priority indicates the priority of the thread (the maximum value is 10, the minimum value is 1, the default value is 5), daemon indicates whether the thread is a daemon thread, and target indicates the task to be executed.
 The following are commonly used methods in the Thread class:
The following are several methods related to the running status of the thread:
1) start method
Start() is used to start a thread. When the start method is called, the system will start a new thread to perform user-defined subtasks. In this process, the required resources will be allocated to the corresponding thread. .
 2) run method
The run() method does not need to be called by the user. After starting a thread through the start method, when the thread obtains the CPU execution time, it enters the run method body. to perform specific tasks. Note that if you inherit the Thread class, you must override the run method and define the specific tasks to be performed in the run method.
 3) sleep method
The sleep method has two overloaded versions:
Sleep is equivalent to letting the thread sleep, handing over the CPU, and letting the CPU perform other tasks.
But one thing to note is that the sleep method will not release the lock. That is to say, if the current thread holds a lock on an object, other threads will not be able to access the object even if the sleep method is called. It will be clear when you look at the following example:
1
2
3
##sleep(long millis) //The parameter is milliseconds
sleep(long millis,int nanoseconds) //The first parameter is milliseconds, the second parameter is nanoseconds
##1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public class Test {
                                                                                                                                                                               
# private Object object = new Object();
public static void main(String[] args) throws IOException {
Test test = new Test();
MyThread thread1 = test.new MyThread();
MyThread thread2 = test.new MyThread();
thread1.start();
                                             thread2.start();                                                                    
# public void run() {
synchronized (object) {
i++;
System.out.println("i:"+i);
try ).sleep(10000);
                                                                   System.out.println ("Thread"+Thread.currentThread().getName()+"Sleep End");
        i++;
               System.out.println("i:"+i);
                                  
##                                                                            
Output result:

As can be seen from the above output result, when Thread-0 enters the sleep state, Thread-1 Didn't perform specific tasks. Only when Thread-0 completes execution, and Thread-0 releases the object lock, does Thread-1 begin execution.
Note that if the sleep method is called, the InterruptedException must be caught or thrown to the upper layer. When the thread sleep time is up, it may not be executed immediately because the CPU may be performing other tasks at this time. So calling the sleep method is equivalent to putting the thread into a blocking state.
 4) yield method
Calling the yield method will cause the current thread to hand over CPU permissions and let the CPU execute other threads. It is similar to the sleep method and does not release the lock. However, yield cannot control the specific time to hand over the CPU. In addition, the yield method can only allow threads with the same priority to have the opportunity to obtain CPU execution time.
Note that calling the yield method does not put the thread into the blocking state, but returns the thread to the ready state. It only needs to wait to reacquire the CPU execution time, which is different from the sleep method.
5) join method
The join method has three overloaded versions:
1
2
3
join()
join(long millis) // The parameter is milliseconds
join(long millis,int nanoseconds) //The first parameter is milliseconds, the second parameter is nanoseconds
If the thread.join method is called in the main thread, the main method will wait for the thread thread to complete execution or wait for a certain period of time. If the join method without parameters is called, wait for the thread to complete execution. If the join method with a specified time parameter is called, wait for a certain event.
Look at the following example:
##1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public class Test {
                                                                                                                                                                                                                                                                                      ("Enter the thread"+Thread.currentThread().getName());
Test test = new Test();
MyThread thread1 = test.new MyThread();
       thread1.start();
                                                                                                                                                                                                                                                                                 because through
# thread1.join ();
System.out.println ("thread"+thread.currentthRead (). Getname ()+"continues to execute");
##} Catch (InterruptedException e) {
                                                                                                                                            TODO Auto-generated catch block
              e.printStackTrace(); #    
       class MyThread extends Thread{
                                                                                                                                                                                                                                                                           .currentThread ().getName());
# // Todo: Handle Exception
}
System.out.println ("thread"+thread.currentthread (). GetName ()+");
}
}
}
Output result:

It can be seen that when the thread1.join() method is called, the main thread will enter the waiting state. Then wait for thread1 to finish executing before continuing.
Actually calling the join method calls the wait method of Object. This can be known by viewing the source code:
 

Wait method This will cause the thread to enter a blocked state, release the lock held by the thread, and hand over CPU execution permissions.
Since the wait method will cause the thread to release the object lock, the join method will also cause the thread to release the lock held on an object. The specific use of wait method is given in the following article.
6) interrupt method
Interrupt, as the name suggests, means interruption. Calling the interrupt method alone can cause the thread in the blocked state to throw an exception, that is, it can be used to interrupt a thread in the blocked state; in addition, the interrupt method and isInterrupted() method are used to stop the running thread.
Let’s look at an example:
##public class Test {
##1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# Public Static Void Main (String [] ARGS) Throws IOEXCEPTION {
Test Test = New Test ();
# mythread thread = test. new MyThread();
thread.start();
try {
Thread.currentThread().sleep(2000);
} catch (InterruptedException e) {
                                                                                                                                                      Mythread extends thread {
# @Override
Public void run () {
## Try {
## System.out.println ("Enter Sleep Status") ;
                                                                                                                                                                                                                                               
## System.out.println ("Get the Interrupted Abnormal");
##}
System.out.println ("Run method is executed");
}
}
}
Output result:

It can be seen from here that the thread in the blocked state can be interrupted through the interrupt method. So can a thread in a non-blocking state be interrupted? Look at the following example:
#1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class Test {
           
      public static void main(String[] args) throws IOException  {
Test test = new Test();
MyThread thread = test.new MyThread();
thread.start();
try {
                                                                                                                                  to  ();
}
class MyThread extends Thread{
@Override
public void run() {
int i = 0;
while(i System.out.println(i+" while loop");
i++;
}
}
}
}
When you run this program, you will find that the while loop will continue to run until the value of variable i exceeds Integer.MAX_VALUE. Therefore, calling the interrupt method directly cannot interrupt the running thread.
But if the running thread can be interrupted with isInterrupted(), because calling the interrupt method is equivalent to setting the interrupt flag to true, then you can interrupt the thread by calling isInterrupted() to determine whether the interrupt flag is set. implement. For example, the following code:
6
#1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class Test {
             
##         public static void main(String[] args) throws IOException  {
Test test = new Test();
MyThread thread = test.new MyThread();
thread.start();
try {
                                                                                                              out. interrupt();
}
class MyThread extends Thread{
@Override
public void run() {
int i = 0;
while(!isInterrupted() && i
System.out.println(i+" while loop");
                                                                                                                                                                         
## When you run it, you will find that after printing several values, the while loop stops printing.
However, it is generally not recommended to interrupt the thread in this way. Generally, an attribute isStop is added to the MyThread class to mark whether to end the while loop, and then the value of isStop is determined in the while loop.
##1
2
3
4
5
7
8
9
10111213
14
class MyThread extends Thread{
private volatile boolean isStop = false;
                                                                                                                                     ’ ’ ’ ‐ to Boolean boolean ’ s ‐ ‐ ‐ ‐ ‐                                                                                                      
#         i++;
                                                                                                                                                                                                                      through stop;
}
}
Then you can terminate the while loop by calling the setStop method outside.
 7) Stop method
The stop method is an obsolete method and it is an unsafe method. Because calling the stop method will directly terminate the call of the run method and throw a ThreadDeath error. If the thread holds an object lock, the lock will be completely released, resulting in inconsistent object status. Therefore, the stop method will basically not be used.
8) destroy method
The destroy method is also an obsolete method. Basically not used.
The following are several methods related to thread properties:
1) getId
Used to get the thread ID
2) getName and setName
Used to get or set the thread name.
3) getPriority and setPriority
Used to get and set thread priority.
4) setDaemon and isDaemon
Used to set whether a thread becomes a daemon thread and determine whether a thread is a daemon thread.
The difference between daemon threads and user threads is that the daemon thread depends on the thread that created it, while the user thread does not. To give a simple example: if a daemon thread is created in the main thread, when the main method finishes running, the daemon thread will also die. The user thread will not. The user thread will continue to run until it is completed. In the JVM, a garbage collector thread is a daemon thread.
The Thread class has a commonly used static method currentThread() to obtain the current thread.
Most of the methods in the Thread class have been mentioned above, so how will the method calls in the Thread class cause changes in the thread state? The following picture is an improvement on the above picture:

The above is the detailed content of Java concurrent programming: How to use the Thread class?. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
带你搞懂Java结构化数据处理开源库SPL带你搞懂Java结构化数据处理开源库SPLMay 24, 2022 pm 01:34 PM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于结构化数据处理开源库SPL的相关问题,下面就一起来看一下java下理想的结构化数据处理类库,希望对大家有帮助。

Java中的Runnable和Thread的区别有哪些?Java中的Runnable和Thread的区别有哪些?May 07, 2023 pm 05:19 PM

在java中可有两种方式实现多线程,一种是继承Thread类,一种是实现Runnable接口;Thread类是在java.lang包中定义的。一个类只要继承了Thread类同时覆写了本类中的run()方法就可以实现多线程操作了,但是一个类只能继承一个父类,这是此方法的局限。下面看例子:packageorg.thread.demo;classMyThreadextendsThread{privateStringname;publicMyThread(Stringname){super();this

一起聊聊Java多线程之线程安全问题一起聊聊Java多线程之线程安全问题Apr 21, 2022 pm 06:17 PM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于多线程的相关问题,包括了线程安装、线程加锁与线程不安全的原因、线程安全的标准类等等内容,希望对大家有帮助。

详细解析Java的this和super关键字详细解析Java的this和super关键字Apr 30, 2022 am 09:00 AM

本篇文章给大家带来了关于Java的相关知识,其中主要介绍了关于关键字中this和super的相关问题,以及他们的一些区别,下面一起来看一下,希望对大家有帮助。

Java基础归纳之枚举Java基础归纳之枚举May 26, 2022 am 11:50 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于枚举的相关问题,包括了枚举的基本操作、集合类对枚举的支持等等内容,下面一起来看一下,希望对大家有帮助。

java中封装是什么java中封装是什么May 16, 2019 pm 06:08 PM

封装是一种信息隐藏技术,是指一种将抽象性函式接口的实现细节部分包装、隐藏起来的方法;封装可以被认为是一个保护屏障,防止指定类的代码和数据被外部类定义的代码随机访问。封装可以通过关键字private,protected和public实现。

归纳整理JAVA装饰器模式(实例详解)归纳整理JAVA装饰器模式(实例详解)May 05, 2022 pm 06:48 PM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于设计模式的相关问题,主要将装饰器模式的相关内容,指在不改变现有对象结构的情况下,动态地给该对象增加一些职责的模式,希望对大家有帮助。

Thread在java中怎么生成接口Thread在java中怎么生成接口May 17, 2023 pm 12:49 PM

在java中,说到线程,Thread是必不可少的。线程是一个比过程更轻的调度执行器。为什么要使用线程?通过使用线程,可以将操作系统过程中的资源分配和执行调度分开。每个线程不仅可以共享过程资源(内存地址、文件I/O等),还可以独立调度(线程是CPU调度的基本单位)。说明1、Thread是制作线程最重要的类,这个词本身也代表线程。2、Thread类实现了Runnable接口。实例publicclassThreadDemoextendsThread{publicvoidrun(){for(inti=0

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment