Summary of basic knowledge of java multithreading (with code)
This article brings you a summary of the basic knowledge of Java multi-threading (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Java main thread name
A program we start can be understood as a process. A process contains a main thread, and a thread can be understood as a subtask. Java You can get the default main thread name through the following code.
1 |
|
The running result is main, which is the name of the thread and not the main method. The main method is executed through this thread.
Two ways to create threads
1. Inherit the Thread class
1 2 3 4 5 6 |
|
2. Implement the Runnable interface
1 2 3 4 5 6 |
|
Thread implements the Runnable interface. And runs in multiple threads , the execution order of the code has nothing to do with the calling order. In addition, if the start method is called multiple times, java.lang.IllegalThreadStateException will be thrown
currentThread method
Returns which thread the current code is being used by Call the .
1 2 3 4 5 6 7 8 9 10 11 |
|
1 2 |
|
isAlive method
to determine whether the current thread is active.
1 2 3 4 5 6 7 8 |
|
1 2 3 4 5 6 |
|
The execution result is as follows
1 2 3 4 5 |
|
thread1 will be executed after 1 second. So the output result is false. And Thread.currentThread() and this are the same object. It can be understood that the thread object that executes the current run method is ourselves (this).
If the thread object is constructed as a parameter When the method is passed to the Thread object for start(), the execution result is different from the previous instance. The reason for this difference is still from the difference between Thread.currentThread() and this.
1 2 3 4 5 6 7 8 |
|
Execution results
1 2 3 4 5 |
|
Thread.currentThread().isAlive() is true because Thread.currentThread() returns a thread object, and we also use this object to start the thread, so it is in the active state .
It is easier to understand if this.isAlive() is false, because we execute the run method through the thread started by the thread object. So it is false. It also means that the two are not the same object. .
sleep method
Let the current "executing thread" sleep within the specified number of milliseconds. The "executing thread" can only be Thread.currentThread()
The returned thread.
1 |
|
Stop the thread
Stopping a thread means stopping the operation being done before the thread completes the task, that is, giving up the current operation.
There are the following 3 methods to terminate a running thread in Java:
Use the exit flag to make the thread exit normally, that is, the thread terminates when the run method is completed.
Use the stop method to forcefully terminate the thread, but this method is not recommended.
Use the interrupt method to interrupt the thread.
The thread that cannot be stopped
Calling the interrupt method only marks the current thread as stopping, and does not actually stop the thread.
1 2 3 4 5 6 7 8 9 |
|
1 2 3 4 |
|
We call the interrupt method after two seconds, according to the printed results We can see that the thread does not stop, but after executing 500000 times of this loop, the run method ends and the thread stops.
Judge whether the thread is stopped
After we mark the thread as stopped, we need to judge inside the thread whether the thread is marked as stop, and if so, stop the thread.
Two judgment methods:
Thread.interrupted(); You can also use this.interrupted();
this.isInterrupted();
The following are two Source code of the method:
1 2 3 4 5 6 7 |
|
interrupted()
Method data static method, that is, determine whether the current thread has been interrupted. isInterrupted()
Determine whether the thread has been interrupted.
interrupted()
Key points of the method from the official website.
The interrupt status of the thread is cleared by this method. In other words, if this method is called twice in a row, the second time will return false (except when the current thread is interrupted again after the first call has cleared its interrupt status and before the second call has verified the interrupt status).
Exception stop thread
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
1 2 3 4 |
|
Output results, these are the last few lines:
1 2 3 4 5 6 7 |
|
Of course we can also replacethrow new InterruptedException();
withreturn
. It’s all the same End the thread.
Stop in sleep
If the thread calls the Thread.sleep()
method to make the thread sleep, then we call thread1.interrupt ()
will be thrown after. InterruptedException
Exception.
1 2 3 |
|
Violently stopping the thread
Violently stopping the thread can use the stop
method, but This method is obsolete and is not recommended for the following reasons.
即刻抛出 ThreadDeath 异常, 在线程的run()方法内, 任何一点都有可能抛出ThreadDeath Error, 包括在 catch 或 finally 语句中. 也就是说代码不确定执行到哪一步就会抛出异常.
释放该线程所持有的所有的锁. 这可能会导致数据不一致性.
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 |
|
1 2 3 4 5 6 |
|
输出结果为:
1 |
|
我们在代码中然线程休眠 Thread.sleep(100000); 是为了模拟一些其它业务逻辑处理所用的时间, 在线程处理其它业务的时候, 我们调用 stop 方法来停止线程.
线程是被停止了也执行了 System.out.println(thread1.getUserName() + " " + thread1.getPwd()); 来帮我们输出结果, 但是 this.pwd = "bb"; 并没有被执行.
所以, 当调用了 stop 方法后, 线程无论执行到哪段代码, 线程就会立即退出, 并且会抛出 ThreadDeath 异常, 而且会释放所有锁, 从而导致数据不一致的情况.
interrupt 相比 stop 方法更可控, 而且可以保持数据一致, 当你的代码逻辑执行完一次, 下一次执行的时候, 才会去判断并退出线程.
如果大家不怎么理解推荐查看 为什么不能使用Thread.stop()方法? 这篇文章. 下面是另一个比较好的例子.
如果线程当前正持有锁(此线程可以执行代码), stop之后则会释放该锁. 由于此错误可能出现在很多地方, 那么这就让编程人员防不胜防, 极易造成对象状态的不一致. 例如, 对象 obj 中存放着一个范围值: 最小值low, 最大值high, 且low不得大于high, 这种关系由锁lock保护, 以避免并发时产生竞态条件而导致该关系失效.
假设当前low值是5, high值是10, 当线程t获取lock后, 将low值更新为了15, 此时被stop了, 真是糟糕, 如果没有捕获住stop导致的Error, low的值就为15, high还是10, 这导致它们之间的小于关系得不到保证, 也就是对象状态被破坏了!
如果在给low赋值的时候catch住stop导致的Error则可能使后面high变量的赋值继续, 但是谁也不知道Error会在哪条语句抛出, 如果对象状态之间的关系更复杂呢?这种方式几乎是无法维护的, 太复杂了!如果是中断操作, 它决计不会在执行low赋值的时候抛出错误, 这样程序对于对象状态一致性就是可控的.
suspend 与 resume 方法
用来暂停和恢复线程.
独占
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
1 2 3 4 5 6 7 8 9 10 11 |
|
输出结果:
1 2 |
|
当调用 Thread.currentThread().suspend(); 方法来暂停线程时, 锁并不会被释放, 所以造成了同步对象的独占.
The above is the detailed content of Summary of basic knowledge of java multithreading (with code). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Guide to Square Root in Java. Here we discuss how Square Root works in Java with example and its code implementation respectively.

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Guide to the Armstrong Number in Java. Here we discuss an introduction to Armstrong's number in java along with some of the code.

Guide to Random Number Generator in Java. Here we discuss Functions in Java with examples and two different Generators with ther examples.

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is
