Maison  >  Article  >  Java  >  Résumé des connaissances de base du multithreading Java (avec code)

Résumé des connaissances de base du multithreading Java (avec code)

不言
不言avant
2019-02-21 14:31:042739parcourir

Le contenu de cet article est un résumé des connaissances de base du multi-threading Java (avec code). Il a une certaine valeur de référence. Les amis dans le besoin peuvent s'y référer.

Nom du thread principal Java

Un programme que nous démarrons peut être compris comme un processus. Un processus contient un thread principal et un thread peut être compris comme une sous-tâche. Java Vous pouvez obtenir le nom du thread principal par défaut via le code suivant

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

Le résultat de l'exécution est main. Il s'agit du nom du thread et non de la méthode principale. .

Deux façons de créer des threads

1. Hériter de la classe Thread

public class Thread1 extends Thread {
    @Override
    public void run() {
        System.out.println("qwe");
    }
}

2. Implémenter l'interface Runnable

public class Thread2 implements Runnable {
    @Override
    public void run() {
        System.out.println("asd");
    }
}
Thread implémente l'interface Runnable. Et lors de l'exécution avec plusieurs threads, l'ordre d'exécution du code n'a rien à voir avec l'ordre d'appel. De plus, si la méthode start est appelée plusieurs fois, java.lang.IllegalThreadStateException sera.
méthode currentThread

renvoie Quel thread le code actuel est-il appelé

public class Thread1 extends Thread {

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

    @Override
    public void run() {
        System.out.println("run 方法的打印:" + Thread.currentThread().getName());
    }
}
Thread1 thread1 = new Thread1();
thread1.start();
méthode isAlive

détermine si le thread actuel est utilisé ? est actif.

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"));
    }
}
Thread1 thread1 = new Thread1();

System.out.println("begin == " + thread1.isAlive());
thread1.start();
Thread.sleep(1000);
System.out.println("end == " + thread1.isAlive());
Résultat de l'exécution Comme suit

begin == false
run 方法的打印 Thread.currentThread().isAlive() == true
run 方法的打印 this.isAlive() == true
run 方法的打印 Thread.currentThread() == this == true
end == false
thread1 est exécuté après 1 seconde Donc le résultat de sortie est faux Et Thread.currentThread() et ceci. sont le même objet, ce qui peut être compris comme l'objet thread exécutant la méthode d'exécution actuelle est nous-mêmes (ceci).

Si l'objet thread est transmis à l'objet Thread en tant que paramètre de construction pour le démarrage de start(), le résultat de l'exécution sera différent de l'exemple précédent. La raison de cette différence vient toujours de Thread La différence entre .currentThread() et ceci .

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());
Résultat de l'exécution

begin == false
run 方法的打印 Thread.currentThread().isAlive() == true
run 方法的打印 this.isAlive() == false
run 方法的打印 Thread.currentThread() == this == false
end == false
La raison pour laquelle Thread.currentThread().isAlive() est vraie est que Thread.currentThread() Ce qui est renvoyé est l'objet thread, et nous démarrons également le thread via cet objet, il est donc dans l'état actif

this.isAlive() est plus facile à comprendre s'il est faux, car nous l'avons démarré via l'objet thread. Le thread exécute la méthode run C'est donc faux. Cela signifie également que les deux ne sont pas le même objet. La

méthode de veille

provoque l'exécution du "thread d'exécution" actuel dans le nombre de millisecondes spécifié " Sleep. "Le thread d'exécution" doit être le thread renvoyé par

.

Thread.currentThread()

Arrêter le thread
Thread.sleep(1000);

Arrêter un thread signifie arrêter le thread avant qu'il ne termine l'opération, c'est-à-dire abandonner l'opération en cours

Il y a les. 3 méthodes suivantes pour terminer un thread en cours d'exécution en Java :

    Utilisez l'indicateur de sortie pour rendre le thread Normal Exit, c'est-à-dire que le thread se termine lorsque la méthode d'exécution est terminée.
  1. Utilisez la méthode stop pour terminer de force le fil de discussion, mais cette méthode n'est pas recommandée.
  2. Utilisez la méthode d'interruption pour interrompre le fil.
  3. Le thread qui ne peut pas être arrêté

L'appel de la méthode d'interruption ne fait que mettre un point d'arrêt sur le thread en cours et n'arrête pas réellement le thread.

public class Thread1 extends Thread {
    @Override
    public void run() {

        for(int i = 0; i < 500000; i++) {
            System.out.println(i);
        }
    }
}
Nous appelons la méthode d'interruption deux secondes plus tard. D'après les résultats imprimés, nous pouvons voir que le thread ne s'arrête pas, mais après avoir exécuté 500 000 de cette boucle, la méthode run se termine et le thread s'arrête.
Thread1 thread1 = new Thread1();
thread1.start();
Thread.sleep(2000);
thread1.interrupt();

Déterminer si le fil est arrêté


Après avoir marqué le fil comme arrêté, nous devons déterminer à l'intérieur du fil si le fil est marqué comme arrêté, et si c'est le cas , arrêtez le fil.

Deux méthodes de jugement :

    Thread.interrupted();Vous pouvez également utiliser this.interrupted();
  1. this .isInterrupted();
  2. Ce qui suit est le code source des deux méthodes :

    public static boolean interrupted() {
        return currentThread().isInterrupted(true);
    }
    
    public boolean isInterrupted() {
        return isInterrupted(false);
    }
Méthode statique des données de méthode , qui consiste à déterminer si le fil de discussion actuel a été interrompu .

Déterminez si le fil de discussion a été interrompu interrupted()isInterrupted() Points clés de la méthode

du site officiel
L'état d'interruption de. le thread est effacé par cette méthode. En d'autres termes, si cette méthode est appelée deux fois de suite, le deuxième appel retournera false (après que le premier appel ait effacé son statut d'interruption et avant que le deuxième appel n'ait vérifié l'état d'interruption, le fil en cours est à nouveau interrompu). interrupted()
S'arrête anormalement Le fil

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();
        }
    }
}
affiche les résultats, voici les dernières lignes :
Thread1 thread1 = new Thread1();
thread1.start();
Thread.sleep(1000);
thread1.interrupt();

De Bien sûr, nous pouvons également remplacer
i = 195173
i = 195174
i = 195175
线程停止
线程通过 catch 停止
java.lang.InterruptedException
    at Thread1.run(Thread1.java:9)
par
. Cela peut se terminer de la même manière. Thread.throw new InterruptedException();returnArrêtez-vous en veille

Si le fil appelle la méthode

pour créer le fil. sleep, alors nous lancerons une exception

.Thread.sleep()thread1.interrupt()InterruptedExceptionArrêter violemment un fil

java.lang.InterruptedException: sleep interrupted
    at java.lang.Thread.sleep(Native Method)
    at Thread1.run(Thread1.java:8)
Vous pouvez utiliser la méthode

pour arrêter violemment un fil, mais cette méthode est obsolète et déconseillé pour les raisons suivantes.

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

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

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";

    }
}
Thread1 thread1 = new Thread1();
thread1.start();
Thread.sleep(1000);
thread1.stop();

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

输出结果为:

b     aa

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

用来暂停和恢复线程.

独占

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");
    }
}
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){ }

输出结果:

begin
线程 a 被中断

当调用 Thread.currentThread().suspend(); 方法来暂停线程时, 锁并不会被释放, 所以造成了同步对象的独占.


Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Cet article est reproduit dans:. en cas de violation, veuillez contacter admin@php.cn Supprimer