Java多线程基础一

本系列文章转载自:https://www.jianshu.com/p/d901b25e0d4a

线程:程序执行流的最小单元【可以理解为:进程中独立运行的子任务】。
多线程优点:最大限度的利用CPU的空闲时间来处理其他任务。

|-目录
|  创建线程
|  线程运行结果与执行顺序无关
|  线程实例变量与安全问题
|  停止线程
|  线程优先级
|  守护线程
|  线程让步

-创建线程

 线程的创建方式:
1.继承Thread类

public class ThreadCreateDemo1 {
    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start(); //该方法调用多次,出现IllegalThreadStateException
    }
}

class MyThread extends Thread {
    @Override
    public void run() {
        super.run();
        System.out.println("hellow_world!");
    }
}

2.实现Runnable接口

public class ThreadCreateDemo2 {
    public static void main(String[] args) {
        Runnable runnable = new MyRunnable();
        Thread thread = new Thread(runnable);
        thread.start();
    }
}

class MyRunnable implements Runnable {
    public void run() {
        System.out.println("通过Runnable创建的线程!");
    }
}

上述两种创建方式,工作时性质一样。但是建议使用实现Runable接口方式。解决单继承的局限性。

-线程运行结果与执行顺序无关

 线程的调度是由CPU决定,CPU执行子任务时间具有不确定性。

public class ThreadRandomDemo1 {
    public static void main(String[] args) {
        Thread[] threads = new Thread[10];
        for (int i = 0; i < 10; i++) {
            threads[i] = new RandomThread("RandomThread:" + i);
        }
        for(Thread thread : threads) {
            thread.start();
        }
    }
}

class RandomThread extends Thread {
    
    public RandomThread(String name) {
        super(name);
    }
    
    @Override
    public void run() {
        try {
            Thread.sleep(1000);
            System.out.println(Thread.currentThread().getName());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

以上10个线程,代码按照顺序执行,但是结果可以看出没有按照顺序执行,而且多次执行结果基本不同。

图1-1 随机线程被执行

-线程实例变量与安全问题

  线程之间变量有共享与不共享之分,共享理解为大家都使用同一份,不共享理解为每个单独持有一份。
  1.共享数据情况,5个Thread共用1个runnable

public class ThreadShareVariableDemo {
    public static void main(String[] args) {
        Runnable runnable = new ShareVariableRunnable();
        Thread[] threads = new Thread[5];
        for (int i = 0; i < 5; i++) {
            threads[i] = new Thread(runnable, "thread:" + (i+1));
        }
        for (Thread thread : threads) {
            thread.start();
        }
    }
}

class ShareVariableRunnable implements Runnable {
    private int count = 5;
    
    public void run() {
        System.out.println("" + Thread.currentThread().getName() + ",count:" + count--);
    }
}

 图1-2 线程共享变量

                                                   图1-3 线程共享变量安全  

从上图结果可以看出,count变量是共享的,不然都会打印5。但是也发现了一点thread:1 与 thread:2 打印值一样,该现象就是我们通常称为的脏数据【多线程对同一变量进行读写操作不同步产生】。
  解决方案在访问变量方法中增加synchronized关键字:

class ShareVariableRunnable implements Runnable {
    private int count = 5;
    
    public synchronized void run() {
        System.out.println("" + Thread.currentThread().getName() + ",count:" + count--);
    }
}

                                                图1-3 线程共享变量安全

如图每次打印count都是正常递减,这里解释一下synchronized关键字,含有synchronized关键字的这个方法称为“互斥区” 或“临界区”,只有获得这个关键字对应的锁才能执行方法体,方法体执行完自动会释放锁。

-停止线程

 终止正在运行的线程方法有三种:
  1)使用退出标志,使线程正常的执行完run方法终止。
  2)使用interrupt方法,使线程异常,线程进行捕获或抛异常,正常执行完run方法终止。
  3)使用stop方法强制退出(不建议)。
 这里主要说明前两种方法;
1.使用退出标志方法

public class ThreadVariableStopDemo {
    public static void main(String[] args) throws InterruptedException {
        VariableStopThread thread = new VariableStopThread("thread_1");
        thread.start();
        Thread.sleep(1);
        thread.Stop();  //注意这里和start执行的是同一个线程,如果是不同线程会有各自的工作内存
    }
}

class VariableStopThread extends Thread {
    private boolean interrupt = true;
    
    public VariableStopThread(String name) {
        super(name);
    }
    
    public void run() {
        System.out.println(Thread.currentThread().getName() + ":线程开始运行!");
        int i = 0;
        while(interrupt) {
            System.out.println("" + (i++));
        }
        System.out.println("我停止了! timer:" + System.currentTimeMillis());
    }
    
    public void Stop() {
        System.out.println(Thread.currentThread().getName() + ":线程设置了停止! timer:" + System.currentTimeMillis());
        this.interrupt = false;
    }
}

                                                      图1-4 线程退出 

Thread_1中启动了一个while循环,一直打印i的累加值。main线程在sleep 1ms后设置Thread_1停止标志。Thread_1 while循环判断条件不符合正常执行完run方法结束。从【图1-4 线程退出】中可以看出设置完停止标志后13还是正常打印,原因是因为while方法体中是原子操作,不能直接打断。
  在使用终止线程方法一时,个人建议代码这么修改更符合Java API规范也避免线程死循环问题【后面章节会介绍】。

public class ThreadVariableStopDemo {
    public static void main(String[] args) throws InterruptedException {
        VariableStopThread thread = new VariableStopThread("thread_1");
        thread.start();
        Thread.sleep(10);
        thread.interrupt();  //发送中断信号
    }
}

class VariableStopThread extends Thread {
    
    public VariableStopThread(String name) {
        super(name);
    }
    
    public void run() {
        System.out.println(Thread.currentThread().getName() + ":线程开始运行!");
        while(!isInterrupted()) { //变为false,跳出循环
        }
        System.out.println("我停止了! timer:" + System.currentTimeMillis());
    }
    
}

2.使用interrupt方法

public class ThreadInterruptDemo {
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new InterruptThread("thread_1");
        thread.start();
        Thread.sleep(1);
        System.out.println(thread.getName() + "线程设置:interrupt");
        thread.interrupt();  //发送中断信号
    }
}

class InterruptThread extends Thread {
    
    public InterruptThread(String name) {
        super(name);
    }
    
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "线程开始!");
        for(int i =0; i < 1000; i++) {
            try {
                Thread.sleep(0);  //收到中断信号会扔出InterruptedException
                System.out.println("" + (i + 1));
            } catch (InterruptedException e) {
                //捕获异常后,isInterrupted()信号会被擦除,又变回false(没有中断信号时默认为false)
                System.out.println(Thread.currentThread().getName() + "线程捕获异常,退出循环!");
                break;
            }
        }
        System.out.println(Thread.currentThread().getName() + "线程结束!");
    }
}

从上图可以看出线程正常退出,但是发现一点循环结构体后面一句打印也打印了,解决这个问题的方案有两个: 

1.异常法

@Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "线程开始!");
        try {
            for(int i = 0; i < 1000; i++) {
                if(Thread.currentThread().interrupted()) {
                 //和isInterrupted()区别不大,上面的是静态方法,收到中断信号都变为true
                    System.out.println(Thread.currentThread().getName() + "线程停止状态!");
                    throw new InterruptedException();
                }
                Thread.sleep(0);
                System.out.println("" + (i + 1));
            }
            System.out.println(Thread.currentThread().getName() + "线程结束!");
        } catch (InterruptedException e) {
            System.out.println(Thread.currentThread().getName() + "线程捕获异常,退出循环!");
            e.printStackTrace();
        }
    }

 

 代码有两个关键点:
  1)for循环外捕获异常【这是程序的关键点】
  2)判断设置了interrupted标志则抛出异常。
2.return法

@Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "线程开始!");
        try {
            for(int i = 0; i < 1000; i++) {
                Thread.sleep(0);
                System.out.println("" + (i + 1));
            }
        } catch (InterruptedException e) {
            System.out.println(Thread.currentThread().getName() + "线程捕获异常,退出循环!");
            e.printStackTrace();
            return;
        }
        System.out.println(Thread.currentThread().getName() + "线程结束!");
    }

这个方法相对简单,也比较常用。两种方法结果都一样直接退出不进行后续工作,两种方法依据功能需求选择。 

-线程优先级

  线程优先级范围为1-10,API提供等级分为:低(MIN_PRIORITY = 1),中(NORM_PRIORITY=5),高(MAX_PRIORITY=10)。
 线程优先级有以下特点:
  1)继承特性【线程A中启动线程B,线程B继承了A的优先级】;
  2)随机性【线程调度的顺序不一定是根据优先级,具有随机性】;

public class ThreadPriorityDemo {
    public static void main(String[] args) {
        Thread thread = new ThreadPriority("thread_1<<<<");
        Thread thread_1 = new ThreadPriority(">>>thread_2");
        thread_1.setPriority(Thread.MIN_PRIORITY); //<设置线程优先级
        thread.setPriority(Thread.MAX_PRIORITY);
        thread_1.start();
        thread.start();
    }
}

class ThreadPriority extends Thread {
    public ThreadPriority(String name) {
        super(name);
    }
    
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println("" + Thread.currentThread().getName() + ",number:" + i + ",Priority:" + Thread.currentThread().getPriority());
        }
    }
}

运行的很给力,以下体现了两个问题:①线程运行顺序与代码执行顺序无关。②线程优先级具有随机性,不是优先级高的就先完成。 

public class ThreadPriorityDemo {
    public static void main(String[] args) {
        Thread thread = new ThreadPriority("thread_1<<<<");
        Thread thread_1 = new ThreadPriority(">>>thread_2");
//      thread_1.setPriority(Thread.MIN_PRIORITY); //<取消设置线程优先级
        thread.setPriority(Thread.MAX_PRIORITY);
        thread_1.start();
        thread.start();
        System.out.println("" + Thread.currentThread().getName() + ",Priority:" + Thread.currentThread().getPriority());
    }
}

class ThreadPriority extends Thread {
    public ThreadPriority(String name) {
        super(name);
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            try {
                Thread.sleep(1);
                System.out.println("" + Thread.currentThread().getName() + ",number:" + i + ",Priority:" + Thread.currentThread().getPriority());
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

 从上图可以看出thread_2与main线程优先级一样都是5,原因是main线程中启动了thread_2,thread_2继承了mian线程的优先级

-守护线程

守护线程顾名思义是一个线程守护另一个线程【此线程为非守护线程】,故守护的线程称为守护线程,被守护的线程称为非守护线程。作用是为其他线程运行提供便利服务

public class DaemonThreadDemo {
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new DaemonThread();
        thread.setDaemon(true); //这一步不设置的话DaemonThread会死循环一直执行
        thread.start();
        System.out.println("" + Thread.currentThread().getName() + "停止运行!" );
    }
}

class DaemonThread extends Thread {
    @Override
    public void run() {
        while (true) {
            System.out.println("DaemonThread 正在运行!");
        }
    }
}

 

从上图可以看出,主线程停止DaemonThread线程也相应的停止了,但不是立即停止 

-线程让步

  线程让步【yield方法】让当前线程释放CPU资源,让其他线程抢占。

public class ThreadYieldDemo {
    public static void main(String[] args) {
        Thread thread = new ThreadYield();
        thread.start();
    }
}
class ThreadYield extends Thread {
    @Override
    public void run() {
        long time_start = System.currentTimeMillis();
        for(int i = 0; i < 500000; i++) {
            Math.random();
//          Thread.yield();
        }
        long time_end = System.currentTimeMillis();
        System.out.println("用时:" + (time_end - time_start));
    }
}

 

线程正常耗时

线程让步耗时

从以上两图可以看出,线程的让步操作比不让步耗时长

-总结

  本篇主要介绍线程API的基础功能,比较常用的线程创建,线程安全,停止线程。只有掌握这些基础才能更好的服务后面线程知识。

猜你喜欢

转载自blog.csdn.net/qq_35572013/article/details/127957958