Java工作知识

Java多线程与并发

2019-07-01  本文已影响2人  谁家的猪

进程和线程的区别

进程和线程的由来

image.png

进程是资源分配的最小单位,线程是CPU调度的最小单位

总结

Java进程和线程的关系

进程间通信

Thread中的run和start的区别

Thread和Runnable的关系

public class MyRunnable implements Runnable {

    private String name;

    public MyRunnable(String name){

        this.name = name;

    }

    @Override

    public void run() {

        for (int i = 0; i < 10; i++) {

            System.out.println("Thread start:" + this.name + ",i=" + i);

        }

    }

    public static void main(String[] args) {

        MyRunnable mr1 = new MyRunnable("Runnable1");

        MyRunnable mr2 = new MyRunnable("Runnable2");

        MyRunnable mr3 = new MyRunnable("Runnable3");

        Thread t1 = new Thread(mr1);

        Thread t2 = new Thread(mr2);

        Thread t3 = new Thread(mr3);

        t1.start();

        t2.start();

        t3.start();

    }

}

如何给run()方法传参

如何实现处理线程的返回值

import java.util.concurrent.*;

/**

* @author lijiayin

*/

public class MyCallable implements Callable<String> {

    @Override

    public String call() throws Exception {

        String value = "test";

        System.out.println("Ready to work");

        Thread.sleep(5000);

        System.out.println("Work finish");

        return value;

    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        FutureTask<MyCallable> futureTask = new FutureTask(new MyCallable());

        new Thread(futureTask).start();

        if(!futureTask.isDone()){

            System.out.println("Work not finish");

        }

        System.out.println("return value : " + futureTask.get());

        ExecutorService executorService = Executors.newCachedThreadPool();

        Future<String> future = executorService.submit(new MyCallable());

        if(!future.isDone()){

            System.out.println("Work not finish");

        }

        try{

            System.out.println("return value : " + future.get());

        }catch (Exception e){

            e.printStackTrace();

        }finally {

            executorService.shutdown();

        }

    }

}

线程的状态

sleep和wait的区别

基本的差别

最主要的本质区别

notify和notifyAll的区别

两个概念

结论

yield

概念

当调用Thread.yield()函数时,会给线程调度器一个当前线程愿意让出CPU使用的暗示,但是线程调度器可能会忽略这个暗示。

对锁行为没有影响。

interrupt函数

通知线程应该中断了

需要被调用的线程配合中断

image.png
上一篇 下一篇

猜你喜欢

热点阅读