• 多线程基础二(线程的启动、终止,线程面临的三种问题)


    一、线程的启动、终止方式

      启动: start native(调用外部接口启动)

        终止:    stop(类似kill,暴力终止)  interrupt 中断的方式 通过指令的方式 volatile boolean stop = false;

    public class InterruptDemo {

    private static int i;
    public static void main(String[] args) {
    Thread thread = new Thread(()->{
    while(!Thread.currentThread().isInterrupted()){//判断是否有interrupt标识
    i++;
    }
    System.out.println(i);
    },"interrupt");
    thread.start();
    try {
    TimeUnit.SECONDS.sleep(1);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    thread.interrupt();//设置interrupt标识为true
    System.out.println(Thread.interrupted());
    }
    }

    二、线程的面临的三大问题
      
    (1)可见性问题
      
    private volatile static boolean stop = false;可见性
    //private static boolean stop = false;
    //main主线程
    public static void main(String[] args) throws InterruptedException {
    //thread子线程
    Thread thread = new Thread(()->{
    int i = 0;
    while (!stop){
    i++;
    }
    System.out.println(i);
    });
    thread.start();
    TimeUnit.SECONDS.sleep(1);
    stop = true;//主线程改变值,子线程不可见,加上volatile后子线程可见
    }

    (2)原子性问题
        
    private static int count = 0;

    public static void inc(){
    try {
    Thread.sleep(1);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    count++;
    }
    public static void main(String[] args) throws InterruptedException {

    for (int i=0 ; i<1000;i++){
    new Thread(AtomicDemo::inc).start();
    }
    Thread.sleep(4000);
    System.out.println("运行结果:"+count);
    }

    运行结果却不一定能够是1000,之间相互影响

    (3)有序性问题
    根据编译,缓存的一致性问题等因素,程序的执行可能不会按照所编写的执行。

    JMM规范了上述线程的三个问题
  • 相关阅读:
    第一次做的破网页
    c++初学指针
    eskibana
    有关JSON以及JSON在PHP中的应用
    比较全的log4j 配置
    验证码类
    PHP 兼容 Curl/Socket/Stream 的 HTTP 操作类
    PHP缓存技术
    Fatal error: Call to undefined function curl_init()解决方案
    socket基础
  • 原文地址:https://www.cnblogs.com/flgb/p/9902706.html
Copyright © 2020-2023  润新知