21.1并发(1)

2020-03-08  本文已影响0人  云木杉

并发编程

一直以为并发只是Java的一部分,没有想到这部分这么多,所以只能以系列的来记录,因为一篇的话根本描述不完,预计一个月的时间去了解实践。像书中讲的那样,你即使不了解它,你的程序也许也会正常的执行,偶尔出个问题,你也会觉得获取是其他地方的问题,久而久之并发的问题就不了了之了,但肯定会酝酿一个更大的bug来迎接你。

也是因为新环境的问题,认识到自己的不足,即使以前我也看过很多遍的,每次看的都比较煎熬,那么痛苦的环境下就放弃了,也是因为太急功近利,没有把心沉下来,好好的去探索里面的奥秘,像书中而言,就当学习一门新的语言了。


并发的作用

基本的线程机制

public class LiftOff implements Runnable {

        // 成员变量 每个对象都有自己在内存中的一片区域,所以每个对象都有自己的成员
    protected int countDown = 10; // Default
    // 静态成员 成员不属于对象 存在于内存(静态储存区)中 
    private static int taskCount = 0;
    // 成员 final 对象只初始化一次
    private final int id = taskCount++;

    public LiftOff() {
    }

    public LiftOff(int countDown) {
        this.countDown = countDown;
    }

    public String status() {
        return "#" + id + "(" +
                (countDown > 0 ? countDown : "Liftoff!") + "), ";
    }

    public void run() {
        try {
            while (countDown-- > 0) {
                System.out.print(status());
                Thread.yield();
                TimeUnit.MILLISECONDS.sleep(1);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {

       // LiftOff liftOff = new LiftOff();
       // 一个普通的run方法执行
       // liftOff.run(); 
       
       // LiftOff的run方法是执行在新线程的
       // 构造函数执行在新线程的开启线程(main线程)
       // Thread thread = new Thread(new LiftOff());
       // 开启一个线程 执行任务的run方法
       // thread.start(); 
       
    }

}
class Sleeper extends Thread {
    private int duration;

    public Sleeper(String name, int sleepTime) {
        super(name);
        duration = sleepTime;
        start();
    }

    public void run() {
        try {
            sleep(duration);
        } catch (InterruptedException e) {
            print(getName() + " was interrupted. " +
                    "isInterrupted(): " + isInterrupted());
            return;
        }
        print(getName() + " has awakened");
    }
}

class Joiner extends Thread {
    private Sleeper sleeper;

    public Joiner(String name, Sleeper sleeper) {
        super(name);
        this.sleeper = sleeper;
        start();
    }

    public void run() {
        try {
            sleeper.join();
        } catch (InterruptedException e) {
            print("Interrupted");
        }
        print(getName() + " join completed");
    }
}

public class Joining {
    public static void main(String[] args) {
        Sleeper sleepy = new Sleeper("Sleepy", 1500);
        Sleeper grumpy = new Sleeper("Grumpy", 1500);
        Joiner dopey = new Joiner("Dopey", sleepy);
        Joiner doc = new Joiner("Doc", grumpy);
        grumpy.interrupt();
    }
}
class ExceptionThread2 implements Runnable {
   public void run() {
       throw new NullPointerException();
   }
}

class MyUncaughtExceptionHandler implements
       Thread.UncaughtExceptionHandler {
   public void uncaughtException(Thread t, Throwable e) {
       System.out.println("caught " + e);
   }
}

class HandlerThreadFactory implements ThreadFactory {
   public Thread newThread(Runnable r) {
       Thread t = new Thread(r);
       t.setUncaughtExceptionHandler(
               new MyUncaughtExceptionHandler());
       return t;
   }
}

public class CaptureUncaughtException {
   public static void main(String[] args) {
       ExecutorService exec = Executors.newCachedThreadPool(
               new HandlerThreadFactory());
       exec.execute(new ExceptionThread2());
   }
}

也可以通过自定义异常处理器处理

public class CaptureUncaughtException {
    public static void main(String[] args) {
        ExecutorService exec = Executors.newCachedThreadPool(
                new HandlerThreadFactory());
        exec.execute(new ExceptionThread2());
    }
}

class HandlerThreadFactory implements ThreadFactory {
    public Thread newThread(Runnable r) {
        Thread t = new Thread(r);
        t.setUncaughtExceptionHandler(
                new MyUncaughtExceptionHandler());
        return t;
    }
}

class MyUncaughtExceptionHandler implements
      Thread.UncaughtExceptionHandler {
public void uncaughtException(Thread t, Throwable e) {
  System.out.println("caught " + e);
}
}

class ExceptionThread2 implements Runnable {
    public void run() {
        throw new RuntimeException();
    }
}

还有最简单的一种方式,在不存在专有未捕获异常处理器时调用

public class SettingDefaultHandler {
    public static void main(String[] args) {
        Thread.setDefaultUncaughtExceptionHandler(
                new MyUncaughtExceptionHandler());
        ExecutorService exec = Executors.newCachedThreadPool();
        exec.execute(new ExceptionThread());
    }
}

class MyUncaughtExceptionHandler implements
        Thread.UncaughtExceptionHandler {
  public void uncaughtException(Thread t, Throwable e) {
    System.out.println("caught " + e);
  }
}

public class ExceptionThread implements Runnable {
    public void run() {
        throw new RuntimeException();
    }
}

上一篇 下一篇

猜你喜欢

热点阅读