线程与进程学习笔记

本文详细解析了Java中的线程概念,包括线程与进程的区别,以及如何通过继承Thread、实现Runnable接口和使用Callable接口创建线程。还介绍了线程的生命周期状态。
摘要由CSDN通过智能技术生成

    (1)线程与进程

   

        线程:一个在内存中运行的应用程序。每个进程都有自己独立的一块空间,一个进程可以有多个线程。

        线程:是操作系统能够进行运算调度的最小单位。它被包含在进程之中,是进程中的实际运作单位。一条线程指的是进程中一个单一顺序的控制流,一个进程中可以并发多个线程,每条线程并行执行不同的任务。

        所有运行中的任务通常对应一个进程(Process)。当一个程序进入内存运行时,即变成一个进程,堆栈、自己的程序计数器和自己的局部变量,但不拥有系统资源,它与父进程的其他线程共享该进程所拥有的全部资源。

       

    (2)并行并发

   

        串行:排队依次执行。如一台打印机资源,10位同学排队打印文件,排队使用

        并行:同一时刻多条指令在多个处理机上运行。如两台打印机资源,10位同学排队打印文件,此时可以两位同学同时打印

        并发:同一时刻只能有一条指令执行,但多个进程指令被快速轮换执行,使得在宏观上具有多个进程同时执行的效果。

   

    (3)线程的创建

           

        1、继承Thread

   

        Thread

public class Thread implements Runnable {

    //常用构造方法

    public Thread() {

        this(null, null, "Thread-" + nextThreadNum(), 0);

    }

    public Thread(Runnable target) {

        this(null, target, "Thread-" + nextThreadNum(), 0);

    }

    public Thread(Runnable target, String name) {

        this(null, target, name, 0);

    }

    //常用API

    /**

     * 获取线程的状态,返回值是State枚举(见下文)

     */

    public State getState() {

        // get current thread state

        return jdk.internal.misc.VM.toThreadState(threadStatus);

    }

}

     

/**

 * 继承Thread类

   */

   public class MyThread extends Thread{

   @Override

   public void run() {

       System.out.println(Thread.currentThread().getName());

       System.out.println("MyThread Running");

   }

   public static void main(String[] args) {

       MyThread myThread = new MyThread();

       myThread.setName("MyThread");

       myThread.start();

   }

   }

因为Java中类是单继承的,继承了Thread类,就无法继承其他父类,不利于代码扩展

        2.继承Runnable接口

   

        Runnable

public class MyThread2 implements Runnable{

    public static void main(String[] args) {

        MyThread2 myThread2 = new MyThread2();

        Thread thread = new Thread(myThread2);

        thread.start();

    }

    @Override

    public void run() {

        System.out.println("线程执行体");

    }

}

        弊端:

   

        因为Runnable接口中没有start()方法,因此启动线程时,必须将继承了Runnable接口的类的对象通过Thread类的构造进行包装,然后调用Thread#start()方法启动线程。

        run()方法不能抛出异常,如果run()方法中代码抛出异常,程序只能中断,不能通过try...catch进行异常。

        run()方法没有返回值

   

        3.Callable接口

   

        Callable接口

@FunctionalInterface

public interface Callable<V> {

    /**

     * 等价于run()方法,但是该方法有返回值,并且可以抛出异常

     *

     * @return computed result

     * @throws Exception if unable to compute a result

     */

    V call() throws Exception;

}

        Future接口

public interface Future<V> {

    /**

     * 尝试取消一个任务.如果任务已经执行完成,则取消失败 . 当任务没有开始时,可以取消

     * 如果任务已经开始,线程能不能被取消取决于mayInterruptIfRunning参数

     *

     * 当调用完此方法后调用isCancelled(),isDone()方法都会返回true

     * @param mayInterruptIfRunning 如果是true,则正则执行的线程可以被取消,否则

     * 线程被允许执行完成。

     * @return {@code false} 如果返回false则线程没有取消

     * 典型的例如,这个线程已经执行完成。

     * {@code true} otherwise

     */

    boolean cancel(boolean mayInterruptIfRunning);

   

    /**

     * Returns {@code true} 如果任务在任务启动前或者完成过程被取消,则返回true

     * 在完成后取消,并调用该方法时返回false。

     *

     */

    boolean isCancelled();

   

    /**

     * Returns {@code true} 如果任务完成则返回true.

     * 任务被中断,被取消,或者发生异常,都会返回true

     *

     * @return {@code true} if this task completed

     */

    boolean isDone();

   

    /**

     * 如果需要,等待call()方法执行结束后,获取结果

     *

     * @return the computed result

     * @throws CancellationException if the computation was cancelled

     * @throws ExecutionException if the computation threw an

     * exception

     * @throws InterruptedException if the current thread was interrupted

     * while waiting

     */

    V get() throws InterruptedException, ExecutionException;

   

    /**

     * 等待给定时间内获取结果,如果在等待时间内没有获取到结果,则抛出异常

     *

     * @param timeout the maximum time to wait

     * @param unit the time unit of the timeout argument

     * @return the computed result

     * @throws CancellationException if the computation was cancelled

     * @throws ExecutionException if the computation threw an

     * exception

     * @throws InterruptedException if the current thread was interrupted

     * while waiting

     * @throws TimeoutException if the wait timed out

     */

    V get(long timeout, TimeUnit unit)

        throws InterruptedException, ExecutionException, TimeoutException;

}

       

        使用Callable创建线程的步骤

   

        1. 继承Callable接口,并实现call()方法

        2. 创建FutureTask对象,包装Callable的子类对象

        3. 创建Thread类的对象,包装FutureTask对象

        4. 调用Thread#start()方法启动线程

        5. 调用FutureTask#get()方法获取call()方法的返回值

/**

 * Callable创建接口

   */

   //继承Callable接口,并实现call()方法

   public class MyCallable implements Callable {

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

       Callable<String> callable = new MyCallable();

       FutureTask futureTask = new FutureTask(callable);

       Thread thread = new Thread(futureTask,"thread1");

       thread.start();

       //为了让线程thread1尽快执行,让主线程休眠2秒

       TimeUnit.SECONDS.sleep(2);

       System.out.println(futureTask.get());

   }

   @Override

   public Object call() throws Exception {

       TimeUnit.SECONDS.sleep(5);

       return new String("a")+new String("b");

   }

   }

/**

 * Cancle实例

   */

   public class MyCallableCancle implements Callable{

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

       Callable<String> callable = new MyCallable();

       FutureTask futureTask = new FutureTask(callable);

       Thread thread = new Thread(futureTask,"thread1");

       //System.out.println(futureTask.cancel(true));

       System.out.println("--------------");

       thread.start();

       //为了让线程thread1尽快执行,让主线程休眠2秒

       TimeUnit.SECONDS.sleep(2);

       System.out.println("--------------");

       //只关乎在运行过程中的取消状态,参数决定cancel执行与否,与返回值无关

       System.out.println(futureTask.cancel(true));

       System.out.println(futureTask.get());

       //线程执行之后取消 无法取消 返回false

       System.out.println("--------------");

       System.out.println(futureTask.cancel(true));

   }

   @Override

   public Object call() throws Exception {

       TimeUnit.SECONDS.sleep(10);

       return new String("a")+new String("b");

   }

   }

/**

 * isDone实例

   */

   public class MyCallableIsDone implements Callable{

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

       Callable<String> callable = new MyCallable();

       FutureTask futureTask = new FutureTask(callable);

       Thread thread = new Thread(futureTask,"thread1");

       System.out.println("--------------");

       //线程执行前 返回false

       System.out.println(futureTask.isDone());

       thread.start();

       //为了让线程thread1尽快执行,让主线程休眠2秒

       TimeUnit.SECONDS.sleep(2);

       System.out.println("--------------");

       //线程执行过程中返回false

       System.out.println(futureTask.isDone());

       System.out.println(futureTask.get());

       System.out.println("--------------");

       //线程执行之后 返回true

       System.out.println(futureTask.isDone());

   }

   @Override

   public Object call() throws Exception {

       TimeUnit.SECONDS.sleep(5);

       return new String("a")+new String("b");

   }

   }

    线程的生命周期

   

    线程的生命周期就是线程从创建到运行结束的整个过程状态。

public enum State {

        /**

         * 线程创建但未启动

         */

        NEW,

        /**

         * 线程处于该状态,可能是正在运行,

         * 也可能是处于等待状态,在等待处理器分配资源

         */

        RUNNABLE,

   

        /**

         * 线程在等待其他线程释放锁时,会处于该状态

         */

        BLOCKED,

   

        /**

         * Thread state for a waiting thread.

         * A thread is in the waiting state due to calling one of the

         * following methods:

         * <ul>

         *   <li>{@link Object#wait() Object.wait} with no timeout</li>

         *   <li>{@link #join() Thread.join} with no timeout</li>

         *   <li>{@link LockSupport#park() LockSupport.park}</li>

         * </ul>

         *

         * <p>A thread in the waiting state is waiting for another thread to

         * perform a particular action.

         *

         * For example, a thread that has called {@code Object.wait()}

         * on an object is waiting for another thread to call

         * {@code Object.notify()} or {@code Object.notifyAll()} on

         * that object. A thread that has called {@code Thread.join()}

         * is waiting for a specified thread to terminate.

         */

        WAITING,

   

        /**

         * Thread state for a waiting thread with a specified waiting time.

         * A thread is in the timed waiting state due to calling one of

         * the following methods with a specified positive waiting time:

         * <ul>

         *   <li>{@link #sleep Thread.sleep}</li>

         *   <li>{@link Object#wait(long) Object.wait} with timeout</li>

         *   <li>{@link #join(long) Thread.join} with timeout</li>

         *   <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li>

         *   <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>

         * </ul>

         */

        TIMED_WAITING,

   

        /**

         * 线程执行完毕后处于该状态

         */

        TERMINATED;

}

  • 11
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

好教员好

您的鼓励是我前进动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值