zoukankan      html  css  js  c++  java
  • 多线程基础二(线程的启动、终止,线程面临的三种问题)

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

      启动: 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规范了上述线程的三个问题
  • 相关阅读:
    一个关于java线程的面试题
    【Feature】初探Feature
    Foreign Keys in the Entity Framework
    JS keycode
    SQLyog8.3 . 8.4 Enterprise/Ultimate crack
    Win7下使用toad连接oracle出现can't initialize OCI 1
    ADO 数据类型转换表
    简单Jscript(ASP)模版操作文件
    自适应宽度的左右结构DIV+CSS
    一个比较好用的 classic asp Jscript 框架 SmartAsp
  • 原文地址:https://www.cnblogs.com/flgb/p/9902706.html
Copyright © 2011-2022 走看看