Java 读书笔记 21.1并发

并发

终于来到这里了,好开心;

线程定义

public class Liftoff  implements  Runnable{   //接口

    @Override
    public void run() {           //实现run方法

    }
}

public  static  void  main(String []arg){
       //第一种
       Liftoff liftoff = new Liftoff();
       liftoff.run();
       //第二种
       Thread thread = new Thread(new Liftoff());
       thread.start();
       }
 }

Executor

public class MainThread {
   public  static  void  main(String []arg)
   {
       //ExecutorService executorService = Executors.newCachedThreadPool();   // 每一个任务都创建新的线程
       ExecutorService executorService = Executors.newFixedThreadPool(2);   //同时只允许两个线程工作;
       for (int i1 = 0; i1 < i; i1++) {
          //new Thread(new Liftoff()).start();
           executorService.execute(new Liftoff());
       }
       executorService.shutdown();

           System.out.println("wait");

   }

}

Callable

public class TaskWithResult implements Callable<String> {
    public  static  void  main(String []arg)
    {
        ExecutorService executorService = Executors.newCachedThreadPool();
        ArrayList<Future<String>> futures = new ArrayList<>();
        for (int i = 0;i<10;i++)
        {
            futures.add(executorService.submit(new TaskWithResult(i)));
        }
        for (Future<String> fs : futures)
        {

            try {
                System.out.println(fs.get());
            }catch (ExecutionException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                executorService.shutdown();
            }

        }

    }

    private  int id;
    public  TaskWithResult(int id)
    {
        this.id= id;
    }

    @Override
    public String call() throws Exception {    //实现call方法,用以返回值;
        return  "result "+id;
    }
}

优先级

public class Priority  implements  Runnable{
    public  static  void  main(String []arg)
    {
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i=0;i<5;i++)
        {
            executorService.execute(new Priority(Thread.MIN_PRIORITY));
        }
        executorService.execute(new Priority(Thread.MAX_PRIORITY));
        executorService.shutdown();
    }

    private  volatile  double d;
    private  int priority;
    private  int countdown;
    public  Priority(int priority)
    {
        this.priority = priority;
    }
    public  String toString()
    {
        return  Thread.currentThread() + " :"+countdown;
    }
    @Override
    public void run() {
        Thread.currentThread().setPriority(priority);
        while (true) {
            for (int i = 1; i < 100000; i++) {
                d += (Math.PI + Math.E) / (double) i;
                if (i % 1000 == 0)
                    Thread.yield();

            }
            System.out.println(this);
            if (--countdown == 0)
                return;
        }

    }
}
//输出会发现优先级高的线程执行次数远多于一般线程

后台线程

public class SimpleDaemons implements  Runnable {
    @Override
    public void run() {
        try {
            while (true)
            {
                TimeUnit.MILLISECONDS.sleep(500);
                System.out.println(Thread.currentThread()+""+this);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
            System.out.println("interrupt");
        }
        finally {
            System.out.println("finally");      //Main函数退出,后台直接跳出,finally不执行嘞
        }
    }
    public  static  void  main(String []arg) throws InterruptedException {
        for (int i=0;i<10;i++)
        {
            Thread deamon = new Thread(new SimpleDaemons());
            deamon.setDaemon(true);
            deamon.start();
        }
        System.out.println("all daemon started");
        TimeUnit.SECONDS.sleep(5);        //如果主线程不睡,就直接停止了,后台自动停止了
    }

}

后台线程所派生的子线程都是隐式的后台线程;

另外的线程定义方式

public class SimpleThread extends  Thread {
    public SimpleThread() {

        start();
    }
    @Override
    public void run() {
        super.run();
    }
    public  static  void  main(String []arg)
    {
        new SimpleThread();
    }
}

ps:

public class SimpleThread extends  Thread {

    public SimpleThread() {

        start();
        Thread.currentThread().setName("la");  //此时修改的其实是Main这个线程的名字
    }

    @Override
    public void run() {
         Thread.currentThread().setName("la");  //run之后,修改的就是自己的啦;
        System.out.println(Thread.currentThread().getName());
        super.run();
    }
    public  static  void  main(String []arg)
    {
        SimpleThread a= new SimpleThread();
        a.setName("hello");
        System.out.println(Thread.currentThread().getName());
    }
}

join

public class Sleep extends  Thread {
    private  int sleep;
    public  Sleep(String name , int a)
    {
        super(name);
        sleep=a;
        start();
    }
    public  void  run()
    {

        try {

            sleep(sleep);
        } catch (InterruptedException e) {
            System.out.println(getName()+"was interrupt"+isInterrupted());
            return;
        }
        System.out.println(getName() + "has weaken");
    }
}
public class Join extends  Thread {
    private  Sleep sleep;
    public  Join(String name ,Sleep sleep)
    {
        super(name);
       this.sleep=sleep;
        start();
    }
    public  void  run()
    {
        try {
            sleep.join();
        } catch (InterruptedException e) {
            System.out.println("interrupt");
        }
        System.out.println(getName() + " complete");
    }
    public  static  void  main(String []arg)
    {

        Sleep sleep = new Sleep("sleep",1000);
        Sleep grumy = new Sleep("g",1500);
        Join d = new Join("do",sleep);
        Join p = new Join("po",grumy);
        grumy.interrupt();
    }
}
output:
gwas interruptfalse
po complete
sleephas weaken
do complete

异常捕捉

主线程无法捕捉线程的异常,只能通过一个中介,在Thread附着一个异常处理器;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

class ExceptionThread2 implements Runnable {
    public void run() {
        Thread t = Thread.currentThread();
        System.out.println("run() by " + t);
        System.out.println("eh=" + t.getUncaughtExceptionHandler());
        throw new RuntimeException();
    }
}

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

class HandlerThreadFactory implements ThreadFactory {
    @Override
    public Thread newThread(Runnable r) {
        System.out.println(this + " creating new Thread");
        Thread t = new Thread(r);
        System.out.println("created " + t + " ID:" + t.getId());
        t.setUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
        System.out.println("eh=" + t.getUncaughtExceptionHandler());
        return t;
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值