多线程编程核心技术-java多线程技能(1)(下)

简介: 多线程编程核心技术-java多线程技能(1)(下)

7.停止线程


1dc618a0ed9580ce8bfa6facb208c08f.png

这里的停止的概念很容易混淆,看着这本书这段的时候,看的快睡着了,太绕了,没看进去,不过听了首歌<灌篮高手的主题曲>又看了一遍,明白了,哈哈。


1)停不了的线程


public class MyThread  extends Thread {
    @Override
    public void run() {
        super.run();
        for (int i=0;i<5000;i++){
            System.out.println("i=="+(i+1));
        }
    }
    public static void main(String[] args) throws InterruptedException {
        MyThread thread = new MyThread();
        thread.start();
        Thread.sleep(1000);
        thread.interrupt();
    }
}

5d4c6812c8535adbb050f4ddf2e1bce8.png

调用interrupt(),线程没停止。咋停止啊。我也想知道,往下看。


2.判断线程是否是停止状态


interrupted


1dc618a0ed9580ce8bfa6facb208c08f.png


public class MyThread  extends Thread {
    @Override
    public void run() {
        super.run();
        for (int i=0;i<5000;i++){
            System.out.println("i=="+(i+1));
        }
    }
    public static void main(String[] args) throws InterruptedException {
        MyThread thread = new MyThread();
        thread.start();
        Thread.sleep(1000);
        thread.interrupt();
        //Thread.currentThread().interrupt();
        System.out.println(" 是否停止1? = " + thread.interrupted());
        System.out.println(" 是否停止2? = " + thread.interrupted());
        System.out.println("end");
    }
}

1dc618a0ed9580ce8bfa6facb208c08f.png

5d4c6812c8535adbb050f4ddf2e1bce8.png


如何是main中断线程


当前只调用Thread了,里面没有别的线程的时候,他是static的方法。


public static void main(String[] args) {
        Thread.currentThread().interrupt();
        System.out.println("是否停止1: " + Thread.interrupted());
        System.out.println("是否停止1: " + Thread.interrupted());
        System.out.println("end");
    }

1dc618a0ed9580ce8bfa6facb208c08f.png

5d4c6812c8535adbb050f4ddf2e1bce8.png


isInterrupted


public class MyThread  extends Thread {
    @Override
    public void run() {
        super.run();
        for (int i = 0; i < 5000; i++) {
            System.out.println("i==" + (i + 1));
        }
    }
    public static void main(String[] args) throws InterruptedException {
        MyThread thread = new MyThread();
        thread.start();
        Thread.sleep(1000);
        thread.interrupt();
        System.out.println(" 是否停止1? = " + thread.isInterrupted());
        System.out.println(" 是否停止2? = " + thread.isInterrupted());
        System.out.println("end");
    }
}


这是我的结果,书上是


奇怪啊,目前也不知道为啥


3)能停止的线程-异常法


问题:


public class MyThread  extends Thread {
    @Override
    public void run() {
        super.run();
        for (int i=0;i<500000;i++){
            if(this.isInterrupted()){
                System.out.println("已经是停止状态了,我要退出了。");
                break;
            }
            System.out.println("i="+(i+1));
        }
      System.out.println(" 我被输出, 如果此代码是for又继续运行,线程并未停止!");
    }
}
public class Run {
    public static void main(String[] args) throws InterruptedException {
        MyThread thread = new MyThread();
        thread.start();
        Thread.sleep(2000);
        thread.interrupt();
    }
}


解决


public class MyThread  extends Thread {
    @Override
    public void run() {
        super.run();
        try{
            for (int i=0;i<500000;i++){
                if(this.isInterrupted()){
                    System.out.println("已经是停止状态了,我要退出了。");
                    throw  new InterruptedException(); //异常方法解决这个问题
                }
                System.out.println("i="+(i+1));
            }
        }catch (InterruptedException e){
            System.out.println(" 进MyThread.java类run方法中的catch了!");
            e.printStackTrace();
        }
    }
}


4).在沉睡中停止


public class MyThread extends Thread{
    @Override
    public void run() {
        super.run();
        try {
            System.out.println("run begin");
            Thread.sleep(200000);
            System.out.println("run end");
        }catch (Exception e){
            System.out.println("在沉睡中被停止!进入catch!"+this.isInterrupted());
            e.printStackTrace();
        }
    }
}


public class Run {
    public static void main(String[] args) {
        try {
            MyThread myThread = new MyThread();
            myThread.start();
            Thread.sleep(2000);
            myThread.interrupt();
        } catch (InterruptedException e) {
            System.out.println("main catch");
            e.printStackTrace();
        }
    }
}


如果在main测试方法中去掉sleep呢


去掉sleep的实验


public class MyThread extends Thread{
    @Override
    public void run() {
        super.run();
        try {
            for (int i=0;i<100000;i++){
                System.out.println("i="+(i+1));
            }
            System.out.println("run begin");
            Thread.sleep(200000);
            System.out.println("run end");
        }catch (Exception e){
            System.out.println("先停止,再遇到了sleep!进入catch!"+this.isInterrupted());
            e.printStackTrace();
        }
    }
}


public class Run {
    public static void main(String[] args) {
            MyThread myThread = new MyThread();
            myThread.start();
//            Thread.sleep(2000);
            myThread.interrupt();
            System.out.println("end");
    }
}


5)暴力停止stop()


public class MyThread extends Thread {
    private int i =0;
    @Override
    public void run() {
        try {
            while(true){
                i++;
                System.out.println("i=" + i);
                Thread.sleep(1000);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}


public class Run {
    public static void main(String[] args) throws InterruptedException {
        System.out.println(11);
        MyThread thread = new MyThread();
        thread.start();
        Thread.sleep(8000);
        thread.stop();
    }
}

1dc618a0ed9580ce8bfa6facb208c08f.png


6)方法stop()与java.lang.ThreadDeath异常


public class Mythread extends Thread {
    @Override
    public void run() {
        try {
            this.stop();
        }catch (ThreadDeath e){
            System.out.println("进入了catch方法");
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        Mythread thread = new Mythread();
        thread.start();
    }
}

1dc618a0ed9580ce8bfa6facb208c08f.png

5d4c6812c8535adbb050f4ddf2e1bce8.png


7)释放锁的不良后果


public class SynchronizedObject  {
    private String username = "a";
    private String password = "aa";
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    synchronized public void printString(String username, String password){
        try {
            this.username = username;
            System.out.println("22222");
            Thread.sleep(100000);
            this.password = password;
        }catch (InterruptedException e){
            e.printStackTrace();
        }
    }
}


public class MyThread extends Thread {
    private SynchronizedObject object;
    public MyThread(SynchronizedObject object) {
        this.object = object;
    }
    @Override
    public void run() {
        System.out.println(3333);
        object.printString("b", "bb");
    }
}


public class Run  {
    public static void main(String[] args) {
        try{
            SynchronizedObject synchronizedObject = new SynchronizedObject();
            MyThread myThread = new MyThread(synchronizedObject);
            myThread.start();
            System.out.println("111111");
            myThread.sleep(500);
            System.out.println(synchronizedObject.getUsername()+"  "+synchronizedObject.getPassword());
        }catch (InterruptedException e){
            e.printStackTrace();
        }
    }
}


强制stop操作数据不一样。


8)使用return停止线程


public class MyThread extends Thread {
    @Override
    public void run() {
        while(true){
            if(this.isInterrupted()){
                System.out.println("停止了!");
                return;
            }
            System.out.println("timer=="+System.currentTimeMillis());
        }
    }
    public static void main(String[] args) throws InterruptedException {
        MyThread thread = new MyThread();
        thread.start();
        System.out.println(11111);
        Thread.sleep(1);
        thread.interrupt();
    }
}


8 暂停线程


1dc618a0ed9580ce8bfa6facb208c08f.png

a.suspend和resume的使用
public class MyThread extends Thread {
    private int i;
    public int getI() {
        return i;
    }
    public void setI(int i) {
        this.i = i;
    }
    @Override
    public void run() {
        while (true) {
            i++;
        }
    }
    public static void main(String[] args) {
        try {
            MyThread thread = new MyThread();
            thread.start();
            System.out.println("2222222222");
            Thread.sleep(5000);
            //A段
            thread.suspend();
            System.out.println("A==" + System.currentTimeMillis() + " i=" + thread.getI());
            Thread.sleep(5000);
            System.out.println("A==" + System.currentTimeMillis() + " i=" + thread.getI());
            //B段
            thread.resume();
            Thread.sleep(5000);
            //c段
            thread.suspend();
            System.out.println("B==" + System.currentTimeMillis() + " i=" + thread.getI());
            Thread.sleep(5000);
            System.out.println("B==" + System.currentTimeMillis() + " i=" + thread.getI());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}


b.suspend和resume方法的缺点–独占


实验1:

public class SynchronizedObject {
    synchronized public void pringString(){
        System.out.println("begin");
        if(Thread.currentThread().getName().equals("a")){
            System.out.println("a线程永远 suspend 了");
            Thread.currentThread().suspend();
        }
        System.out.println("end");
    }
    public static void main(String[] args) {
        try {
            final SynchronizedObject object = new SynchronizedObject();
            Thread thread1 = new Thread(){
                @Override
                public void run() {
                    object.pringString();
                }
            };
            thread1.setName("a");
            thread1.start();
            Thread.sleep(1000);
            Thread thread2= new Thread(){
                @Override
                public void run() {
                    System.out.println("thread2启动了,但进入不了pringString方法,只打印1个begin");
                    System.out.println("因为pringString()方法被a线程锁定并且永远suspend暂停了");
                }
            };
            thread2.start();
        }catch (InterruptedException e){
            e.printStackTrace();
        }        
    }
}


还有一种独占锁的情况

public class MyThread extends Thread {
    private long i = 0;
    @Override
    public void run() {
        while(true){
            i++;
           // System.out.println(i);
        }
    }
    public static void main(String[] args) throws InterruptedException {
        MyThread thread = new MyThread();
        thread.start();
        Thread.sleep(1000);
        thread.suspend();
        System.out.println("main end");
    }
}

5d4c6812c8535adbb050f4ddf2e1bce8.png

这里打没问题,但是,加一行代码

1dc618a0ed9580ce8bfa6facb208c08f.png

5d4c6812c8535adbb050f4ddf2e1bce8.png

结果显示:根本停不下来!!!

46a9d80a6e05e4e3b19d57a0ee70bcdf.png


c.suspend和resume方法的缺点–不同步


public class MyObject {
    private String username = "1";
    private String password = "11";
    public void setValue(String u, String p){
        this.username = u;
        if(Thread.currentThread().getName().equals("a")){
            System.out.println("停止a线程");
            Thread.currentThread().suspend();
        }
        this.password = p;
    }
    public void printUseranamePassword(){
        System.out.println(username + " " + password );
    }
    public static void main(String[] args) throws InterruptedException {
        final MyObject myObject = new MyObject();
        Thread thread1 = new Thread(){
            @Override
            public void run() {
                myObject.setValue("a", "aa");
            }
        };
        thread1.setName("a");
        thread1.start();
        Thread.sleep(500);
        Thread thread2 = new Thread(){
            @Override
            public void run() {
                myObject.printUseranamePassword();
            }
        };
        thread2.start();
    }
}


9.yiled


1dc618a0ed9580ce8bfa6facb208c08f.png

public class MyThread extends Thread {
    @Override
    public void run() {
        long beginTime = System.currentTimeMillis();
        int count = 0;
        for (int i = 0; i < 5000000; i++) {
            //Thread.yield();
            count = count + (i + 1);
        }
        long endTime = System.currentTimeMillis();
        System.out.println("用时: " + (endTime - beginTime) + "毫秒");
    }
    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start();
    }
}


运行结果:

1dc618a0ed9580ce8bfa6facb208c08f.png

放开Thread.yield();

结果:

5d4c6812c8535adbb050f4ddf2e1bce8.png


10.线程的优先级


46a9d80a6e05e4e3b19d57a0ee70bcdf.png


1)线程优先级的继承性


public class Run {
    public static void main(String[] args) {
        System.out.println("main thread begin priority=" + Thread.currentThread().getPriority());
       // Thread.currentThread().setPriority(6);
        System.out.println("main thread end priority=" + Thread.currentThread().getPriority());
        MyThread1 thread1 = new MyThread1();
        thread1.start();
    }
}


运行结果:

1dc618a0ed9580ce8bfa6facb208c08f.png


打开Thread.currentThread().setPriority(6),

运行结果:

5d4c6812c8535adbb050f4ddf2e1bce8.png


2)优先级具有规则性


46a9d80a6e05e4e3b19d57a0ee70bcdf.png

public class MyThread1 extends Thread {
    @Override
    public void run() {
        long beginTime = System.currentTimeMillis();
        long addResult = 0;
        for (int j = 0; j < 10; j++) {
            for (int i = 0; i < 50000; i++) {
                Random random = new Random();
                random.nextInt();
                addResult = addResult + i;
            }
        }
        long enTime = System.currentTimeMillis();
        System.out.println("1111111===" + (enTime - beginTime));
    }
}
public class Run {
    public static void main(String[] args) {
        for(int i=0;i<5;i++){
            MyThread2 thread2 = new MyThread2();
            thread2.setPriority(1);
            thread2.start();
            MyThread1 thread1 = new MyThread1();
            thread1.setPriority(10);
            thread1.start();
        }
    }
}
public class MyThread2 extends Thread {
    @Override
    public void run() {
        long beginTime = System.currentTimeMillis();
        long addResult = 0;
        for (int j = 0; j < 10; j++) {
            for (int i = 0; i < 50000; i++) {
                Random random = new Random();
                random.nextInt();
                addResult = addResult + i;
            }
        }
        long enTime = System.currentTimeMillis();
        System.out.println("22222===" + (enTime - beginTime));
    }
}


运行结果:

1dc618a0ed9580ce8bfa6facb208c08f.png

5d4c6812c8535adbb050f4ddf2e1bce8.png


3)优先级具有随机性


import java.util.Random;
public class MyThread1 extends Thread {
    @Override
    public void run() {
        long beginTime = System.currentTimeMillis();
        for (int i = 0; i < 1000; i++) {
            Random random = new Random();
            random.nextInt();
        }
        long enTime = System.currentTimeMillis();
        System.out.println("1111111===" + (enTime - beginTime));
    }
}


import java.util.Random;
public class MyThread2 extends Thread {
    @Override
    public void run() {
        long beginTime = System.currentTimeMillis();
        for (int i = 0; i < 1000; i++) {
            Random random = new Random();
            random.nextInt();
        }
        long enTime = System.currentTimeMillis();
        System.out.println("22222===" + (enTime - beginTime));
    }
}


public class Run {
    public static void main(String[] args) {
        for(int i=0;i<5;i++){
            MyThread2 thread2 = new MyThread2();
            thread2.setPriority(5);
            thread2.start();
            MyThread1 thread1 = new MyThread1();
            thread1.setPriority(6);
            thread1.start();
        }
    }
}


4)看谁运行快


public class MyThread1 extends Thread{
    private int count = 0;
    public int getCount() {
        return count;
    }
    @Override
    public void run() {
        while(true){
            count++;
        }
    }
}


public class MyThread2 extends Thread {
    private int count = 0;
    public int getCount() {
        return count;
    }
    @Override
    public void run() {
        while (true){
            count++;
        }
    }
}




1

2

3

4

5

6

7

public class Run {
    public static void main(String[] args) {
        try {
            MyThread1 myThread1 = new MyThread1();
            myThread1.setPriority(Thread.NORM_PRIORITY - 3);
            myThread1.start();
            MyThread2 myThread2 = new MyThread2();
            myThread2.setPriority(Thread.NORM_PRIORITY + 3);
            myThread2.start();
            Thread.sleep(2000);
            myThread1.stop();
            myThread2.stop();
            System.out.println("myThread1==" + myThread1.getCount());
            System.out.println("myThread2==" + myThread2.getCount());
        }catch (InterruptedException e){
          e.printStackTrace();
        }
    }
}



此实验证明:优先级高运行的快。


11.守护线程


1dc618a0ed9580ce8bfa6facb208c08f.png

public class MyThread extends Thread {
    private int i = 0;
    @Override
    public void run() {
        try {
            while (true){
                i++;
                System.out.println("i=" + i);
                Thread.sleep(1000);
            }
        }catch (InterruptedException e){
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        try {
            MyThread myThread = new MyThread();
            myThread.setDaemon(true);
            myThread.start();
            Thread.sleep(5000);
            System.out.println("我离开thread对象也不再打印了,也就是停止了!!");
        }catch (InterruptedException e){
            e.printStackTrace();
        }
    }
}


守护线程也退出了。


至此,多线程入门第一步完了,下一篇文章要了解synchronized的运用!!


相关文章
|
2月前
|
Java 开发者
在Java多线程编程中,选择合适的线程创建方法至关重要
【10月更文挑战第20天】在Java多线程编程中,选择合适的线程创建方法至关重要。本文通过案例分析,探讨了继承Thread类和实现Runnable接口两种方法的优缺点及适用场景,帮助开发者做出明智的选择。
22 2
|
2月前
|
Java
Java中多线程编程的基本概念和创建线程的两种主要方式:继承Thread类和实现Runnable接口
【10月更文挑战第20天】《JAVA多线程深度解析:线程的创建之路》介绍了Java中多线程编程的基本概念和创建线程的两种主要方式:继承Thread类和实现Runnable接口。文章详细讲解了每种方式的实现方法、优缺点及适用场景,帮助读者更好地理解和掌握多线程编程技术,为复杂任务的高效处理奠定基础。
35 2
|
26天前
|
数据采集 Java Python
爬取小说资源的Python实践:从单线程到多线程的效率飞跃
本文介绍了一种使用Python从笔趣阁网站爬取小说内容的方法,并通过引入多线程技术大幅提高了下载效率。文章首先概述了环境准备,包括所需安装的库,然后详细描述了爬虫程序的设计与实现过程,包括发送HTTP请求、解析HTML文档、提取章节链接及多线程下载等步骤。最后,强调了性能优化的重要性,并提醒读者遵守相关法律法规。
56 0
|
1月前
|
监控 安全 Java
Java中的多线程编程:从入门到实践####
本文将深入浅出地探讨Java多线程编程的核心概念、应用场景及实践技巧。不同于传统的摘要形式,本文将以一个简短的代码示例作为开篇,直接展示多线程的魅力,随后再详细解析其背后的原理与实现方式,旨在帮助读者快速理解并掌握Java多线程编程的基本技能。 ```java // 简单的多线程示例:创建两个线程,分别打印不同的消息 public class SimpleMultithreading { public static void main(String[] args) { Thread thread1 = new Thread(() -> System.out.prin
|
1月前
|
安全 Java 调度
Java中的多线程编程入门
【10月更文挑战第29天】在Java的世界中,多线程就像是一场精心编排的交响乐。每个线程都是乐团中的一个乐手,他们各自演奏着自己的部分,却又和谐地共同完成整场演出。本文将带你走进Java多线程的世界,让你从零基础到能够编写基本的多线程程序。
35 1
|
1月前
|
Java 数据处理 开发者
Java多线程编程的艺术:从入门到精通####
【10月更文挑战第21天】 本文将深入探讨Java多线程编程的核心概念,通过生动实例和实用技巧,引导读者从基础认知迈向高效并发编程的殿堂。我们将一起揭开线程管理的神秘面纱,掌握同步机制的精髓,并学习如何在实际项目中灵活运用这些知识,以提升应用性能与响应速度。 ####
48 3
|
2月前
|
Java
Java中的多线程编程:从入门到精通
本文将带你深入了解Java中的多线程编程。我们将从基础概念开始,逐步深入探讨线程的创建、启动、同步和通信等关键知识点。通过阅读本文,你将能够掌握Java多线程编程的基本技能,为进一步学习和应用打下坚实的基础。
|
4月前
|
算法 Java 开发者
Java 编程入门:从零到一的旅程
本文将带领读者开启Java编程之旅,从最基础的语法入手,逐步深入到面向对象的核心概念。通过实例代码演示,我们将一起探索如何定义类和对象、实现继承与多态,并解决常见的编程挑战。无论你是编程新手还是希望巩固基础的开发者,这篇文章都将为你提供有价值的指导和灵感。
|
4月前
|
机器学习/深度学习 Java TensorFlow
深度学习中的图像识别:从理论到实践Java中的多线程编程入门指南
【8月更文挑战第29天】本文将深入探讨深度学习在图像识别领域的应用,从基础理论到实际应用案例,带领读者一步步理解如何利用深度学习技术进行图像识别。我们将通过一个简单的代码示例,展示如何使用Python和TensorFlow库实现一个基本的图像识别模型。无论你是初学者还是有一定经验的开发者,都能从中获得启发和学习。 【8月更文挑战第29天】在Java世界里,线程是程序执行的最小单元,而多线程则是提高程序效率和响应性的关键武器。本文将深入浅出地引导你理解Java多线程的核心概念、创建方法以及同步机制,帮助你解锁并发编程的大门。
|
5月前
|
传感器 数据采集 监控
Java串口编程入门
Java串口编程入门