Table of Contents
currentThread method
isAlive method
sleep method
Stop the thread
The thread that cannot be stopped
Exception stop thread
Stop in sleep
Violently stopping the thread
suspend 与 resume 方法
独占
Home Java javaTutorial Summary of basic knowledge of java multithreading (with code)

Summary of basic knowledge of java multithreading (with code)

Feb 21, 2019 pm 02:31 PM
java

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

System.out.println(Thread.currentThread().getName());

Copy after login

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

public class Thread1 extends Thread {

    @Override

    public void run() {

        System.out.println("qwe");

    }

}

Copy after login

2. Implement the Runnable interface

1

2

3

4

5

6

public class Thread2 implements Runnable {

    @Override

    public void run() {

        System.out.println("asd");

    }

}

Copy after login
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

public class Thread1 extends Thread {

 

    public Thread1() {

        System.out.println("构造方法的打印:" + Thread.currentThread().getName());

    }

 

    @Override

    public void run() {

        System.out.println("run 方法的打印:" + Thread.currentThread().getName());

    }

}

Copy after login

1

2

Thread1 thread1 = new Thread1();

thread1.start();

Copy after login

isAlive method

to determine whether the current thread is active.

1

2

3

4

5

6

7

8

public class Thread1 extends Thread {

    @Override

    public void run() {

        System.out.println("run 方法的打印 Thread.currentThread().isAlive() == " + Thread.currentThread().isAlive());

        System.out.println("run 方法的打印 this.isAlive() == " + this.isAlive());

        System.out.println("run 方法的打印 Thread.currentThread().isAlive() == this.isAlive() == " + (Thread.currentThread() == this ? "true" "false"));

    }

}

Copy after login

1

2

3

4

5

6

Thread1 thread1 = new Thread1();

 

System.out.println("begin == " + thread1.isAlive());

thread1.start();

Thread.sleep(1000);

System.out.println("end == " + thread1.isAlive());

Copy after login

The execution result is as follows

1

2

3

4

5

begin == false

run 方法的打印 Thread.currentThread().isAlive() == true

run 方法的打印 this.isAlive() == true

run 方法的打印 Thread.currentThread() == this == true

end == false

Copy after login

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

System.out.println("begin == " + thread1.isAlive());

//thread1.start();

// 如果将线程对象以构造参数的方式传递给 Thread 对象进行 start() 启动

Thread thread = new Thread(thread1);

thread.start();

 

Thread.sleep(1000);

System.out.println("end == " + thread1.isAlive());

Copy after login

Execution results

1

2

3

4

5

begin == false

run 方法的打印 Thread.currentThread().isAlive() == true

run 方法的打印 this.isAlive() == false

run 方法的打印 Thread.currentThread() == this == false

end == false

Copy after login

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

Thread.sleep(1000);

Copy after login

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:

  1. Use the exit flag to make the thread exit normally, that is, the thread terminates when the run method is completed.

  2. Use the stop method to forcefully terminate the thread, but this method is not recommended.

  3. 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

public class Thread1 extends Thread {

    @Override

    public void run() {

 

        for(int i = 0; i < 500000; i++) {

            System.out.println(i);

        }

    }

}

Copy after login

1

2

3

4

Thread1 thread1 = new Thread1();

thread1.start();

Thread.sleep(2000);

thread1.interrupt();

Copy after login

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:

  1. Thread.interrupted(); You can also use this.interrupted();

  2. this.isInterrupted();

The following are two Source code of the method:

1

2

3

4

5

6

7

    public static boolean interrupted() {

        return currentThread().isInterrupted(true);

    }

     

    public boolean isInterrupted() {

        return isInterrupted(false);

    }

Copy after login

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

public class Thread1 extends Thread {

    @Override

    public void run() {

        try {

            for (int i = 0; i < 500000; i++) {

                if (this.isInterrupted()) {

                    System.out.println("线程停止");

                    throw new InterruptedException();

                }

 

                System.out.println("i = " + i);

            }

        catch (InterruptedException e) {

            System.out.println("线程通过 catch 停止");

            e.printStackTrace();

        }

    }

}

Copy after login

1

2

3

4

Thread1 thread1 = new Thread1();

thread1.start();

Thread.sleep(1000);

thread1.interrupt();

Copy after login

Output results, these are the last few lines:

1

2

3

4

5

6

7

i = 195173

i = 195174

i = 195175

线程停止

线程通过 catch 停止

java.lang.InterruptedException

    at Thread1.run(Thread1.java:9)

Copy after login
Of course we can also replace throw new InterruptedException(); with return. 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

java.lang.InterruptedException: sleep interrupted

    at java.lang.Thread.sleep(Native Method)

    at Thread1.run(Thread1.java:8)

Copy after login

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.

  1. 即刻抛出 ThreadDeath 异常, 在线程的run()方法内, 任何一点都有可能抛出ThreadDeath Error, 包括在 catch 或 finally 语句中. 也就是说代码不确定执行到哪一步就会抛出异常.

  2. 释放该线程所持有的所有的锁. 这可能会导致数据不一致性.

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 Thread1 extends Thread {

 

    private String userName = "a";

    private String pwd = "aa";

 

    public String getUserName() {

        return userName;

    }

 

    public void setUserName(String userName) {

        this.userName = userName;

    }

 

    public String getPwd() {

        return pwd;

    }

 

    public void setPwd(String pwd) {

        this.pwd = pwd;

    }

 

    @Override

    public void run() {

        this.userName = "b";

        try {

            Thread.sleep(100000);

        catch (InterruptedException e) {

            e.printStackTrace();

        }

        this.pwd = "bb";

 

    }

}

Copy after login

1

2

3

4

5

6

Thread1 thread1 = new Thread1();

thread1.start();

Thread.sleep(1000);

thread1.stop();

 

System.out.println(thread1.getUserName() + "     " + thread1.getPwd());

Copy after login

输出结果为:

1

b     aa

Copy after login

我们在代码中然线程休眠 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

public class PrintObject {

    synchronized public void printString(){

        System.out.println("begin");

        if(Thread.currentThread().getName().equals("a")){

            System.out.println("线程 a 被中断");

            Thread.currentThread().suspend();

        }

        if(Thread.currentThread().getName().equals("b")){

            System.out.println("线程 b 运行");

        }

        System.out.println("end");

    }

}

Copy after login

1

2

3

4

5

6

7

8

9

10

11

try{

    PrintObject  pb = new PrintObject();

    Thread thread1 = new Thread(pb::printString);

    thread1.setName("a");

    thread1.start();

    thread1.sleep(1000);

 

    Thread thread2 = new Thread(pb::printString);

    thread2.setName("b");

    thread2.start();

}catch(InterruptedException e){ }

Copy after login

输出结果:

1

2

begin

线程 a 被中断

Copy after login

当调用 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!

Statement of this Website
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

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)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Square Root in Java Square Root in Java Aug 30, 2024 pm 04:26 PM

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

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

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

Armstrong Number in Java Armstrong Number in Java Aug 30, 2024 pm 04:26 PM

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

Random Number Generator in Java Random Number Generator in Java Aug 30, 2024 pm 04:27 PM

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

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

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

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

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

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

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

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

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

See all articles