java Thread

线程的创建
本质上都是实现runnable接口,重写了run方法。

  1. 实现runnable接口
  2. 继承Thread类
  3. 实现callable
  4. 线程池
public class CreatThread {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 实现runnable接口
        new Thread(new MyRun()).start();
        // 继承Thread类
        new MyThread().start();
        // 实现callable
        MyCallable callable = new MyCallable();
        FutureTask<String> task = new FutureTask<>(callable);
        new Thread(task).start();
        System.out.println(task.get());
        // 线程池
        ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(2, 3, 500, TimeUnit.SECONDS, new LinkedBlockingQueue<>(500));
        poolExecutor.execute(() -> System.out.println("ThreadPoolExecutor ..."));
        poolExecutor.shutdown();

        // 常用方式 匿名内部类
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("匿名内部类");
            }
        }).start();
        // lambda
        new Thread(() ->
                System.out.println("lambda")
        ).start();

    }

    public static class MyRun implements Runnable {
        @Override
        public void run() {
            System.out.println("implements Runnable ...");
        }
    }

    public static class MyThread extends Thread {
        @Override
        public void run() {
            System.out.println("extends Thread ...");
        }
    }

    public static class MyCallable implements Callable<String> {
        @Override
        public String call() {
            return "implements Callable ...";
        }
    }
}

线程的状态

  1. new 新建状态
  2. runnable 运行就绪状态
  3. blocked 拿锁失败阻塞状态
  4. waiting 等待状态
  5. time-waiting 时间等待状态
  6. terminated 结束状态
public class ThreadState {
    public static void main(String[] args) throws InterruptedException {
        // new 新建状态
        // newState();

        // runnable 运行就绪状态
        // runnable();

        // blocked 拿锁失败阻塞状态
        // blocked();

        // waiting 等待状态
        //waiting();

        // time_waiting 时间等待状态
        // timeWaiting();

        // terminated  结束状态
        terminated();

        Thread.sleep(500);
    }

    public static void newState() {
        Thread thread = new Thread(() -> {
        });
        System.out.println(thread.getState());
    }

    public static void runnable() {
        Thread thread = new Thread(() -> {
            for (int i = 0; i < 100; i++) ;
        });
        thread.start();
        System.out.println(thread.getState());
    }

    public static void blocked() throws InterruptedException {
        Object o = new Object();
        Thread thread = new Thread(() -> {
            synchronized (o) {
            }
        });
        synchronized (o) {
            thread.start();
            Thread.sleep(100);
            System.out.println(thread.getState());
        }
    }

    public static void waiting() throws InterruptedException {
        Object o = new Object();
        Thread thread = new Thread(() -> {
            synchronized (o) {
                try {
                    o.wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        thread.start();
        Thread.sleep(100);
        System.out.println(thread.getState());
    }

    public static void timeWaiting() throws InterruptedException {
        Thread thread = new Thread(() -> {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        thread.start();
        Thread.sleep(50);
        System.out.println(thread.getState());
    }

    public static void terminated() throws InterruptedException {
        Thread thread = new Thread(() -> {
        });
        thread.start();
        Thread.sleep(100);
        System.out.println(thread.getState());
    }
}

终止线程

  1. stop 线程强制终止 不建议使用
  2. interrupt 线程内部的共享变量控制 推荐使用
  3. 自定义共享变量 不推荐使用
public class StopThread {
    public static void main(String[] args) throws InterruptedException {
        // stop 线程强制终止 不建议使用
        // stop();

        // interrupt 线程内部的共享变量控制  推荐使用
        interrupt();

        // 自定义共享变量 不推荐使用
    }

    public static void stop() throws InterruptedException {
        Thread thread = new Thread(() -> {
            while (true) ;
        });
        thread.start();
        Thread.sleep(10);
        System.out.println(thread.getState());
        thread.stop();
        Thread.sleep(10);
        System.out.println(thread.getState());
    }

    public static void interrupt() throws InterruptedException {
        Thread thread = new Thread(() -> {
            while (!Thread.currentThread().isInterrupted()) ;
        });
        thread.start();
        Thread.sleep(10);
        System.out.println(thread.getState());
        thread.interrupt();
        Thread.sleep(10);
        System.out.println(thread.getState());
    }
}

wait和sleep的区别

  1. sleep属于Thread类中的静态方法,wait是Object类的方法
  2. sleep属于timed_waiting,自动唤醒,wait属于waiting,需要手动唤醒
  3. sleep方法在持有锁时,执行,不会释放锁资源,wait在执行后,会释放锁资源。
  4. sleep在持有锁或者不持有锁时执行,wait方法必须持有锁才可以执行。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值