【java基础】线程

2020-06-12  本文已影响0人  giraffecode9668

java基础 线程

参考详细:Java之多线程

一、创建线程

创建线程常见有两种方式,另外有两种新增方式

1.Thread

    /**
    新建线程方式一:继承Thread,重写run()
     */
    public static void test1(){
        Thread1 thread1 = new Thread1();
        thread1.setName("thread1");
        thread1.start();
    }

    static class Thread1 extends Thread{
        int i;
        @Override
        public void run() {
            while (i < 100){
                ++i;
                System.out.println(this.getName() + " 优先级 "+this.getPriority()+":" + i);
            }
        }
    }

2.Runnable

     /**
     * 新建线程方式二:实现Runnable,实现run();将Runnable作为Thread创建的实参
     */
    public static void test2(){
        Runnable runnable = new Runnable() {
            int i;
            @Override
            public void run() {
                while (i < 100){
                    ++i;
                    System.out.println(Thread.currentThread().getName() + " 优先级 "+Thread.currentThread().getPriority()+":" + i);
                }
            }
        };
        Thread thread2 = new Thread(runnable,"thread2");
        thread2.start();
    }

3.Callable --- JDK5.0新增

     /**
     * 新增·方式三:实现Callable接口,此功能支持有泛型返回值,支持抛出异常,需借助FutureTask类
     */
    public static void test3() throws ExecutionException, InterruptedException {
        Callable callable = getCallable();
        FutureTask<Integer> futureTask = new FutureTask<>(callable);
        Thread thread3 = new Thread(futureTask);
        thread3.start();

        // 返回值
        Integer integer = futureTask.get();
        System.out.println("方式三:main获得结果-"+integer);
    }

    private static Callable getCallable(){
        Callable<Integer> callable = new Callable<Integer>() {
            int i;
            @Override
            public Integer call() throws Exception {
                while (i < 100){
                    ++i;
                    System.out.println(Thread.currentThread().getName() + " 优先级 "+Thread.currentThread().getPriority()+":" + i);
                }
                return i;
            }
        };
        return callable;
    }

4.ThreadPool --- JDK5.0新增

     /**
     * 新增·方式四:使用线程池创建线程
     */
    public static void test4() throws ExecutionException, InterruptedException {
        ExecutorService service = Executors.newFixedThreadPool(5);
        ThreadPoolExecutor service1 = (ThreadPoolExecutor)service;
        Callable callable = getCallable();
        Future future = service1.submit(callable);
        System.out.println("方式四:main获得结果-"+future.get());
        service.shutdown();
    }

     private static Callable getCallable(){
        Callable<Integer> callable = new Callable<Integer>() {
            int i;
            @Override
            public Integer call() throws Exception {
                while (i < 100){
                    ++i;
                    System.out.println(Thread.currentThread().getName() + " 优先级 "+Thread.currentThread().getPriority()+":" + i);
                }
                return i;
            }
        };
        return callable;
    }

步骤:

1)提供指定线程池
ExecutorService service = Executors.newXXXThreadPool()

设置线程池属性
ThreadPoolExecutor service1 = ()service;
service1.setXXX

2)执行指定线程的操作,需要提供实现Runnable接口或Callable接口库实现类的对象
service.execute(xxx); // xxx为实现Runnable接口的类的对象
service.submit(xxx); // xxx为实现Callable接口的类的对象,返回结果Future类

3)关闭连接池
service.shutdown();

二、线程属性方法

1.Thread类的有关方法

1)start():启动当前线程,调用当前线程的run()
2)run():通常需要重写Thread类中的此方法,将创建的线程需要处理的逻辑写在这里
3)currentThread():静态方法,返回执行当前代码的线程 this = Thread.currentThread()
4)getName():获得当前线程的名字
5)setName():设置当前线程的名字
6)yield():释放当前cpu的执行权
7)join():在线程a中调用线程b的join(),此时线程a就进入阻塞状态,直到线程b完全执行完成以后,线程a就是阻塞状态
8)stop():已过时。当执行此方法,强制结束当前线程
9)sleep(long millitime):让当前线程“睡眠”指定millitime毫秒。在指定的毫秒内,当前线程阻塞状态。
10)isAlive():判断当前线程是否存活

2.线程优先级

1)等级:
MAX_PRIORITY:10,MIN_PRIORITY:1,NORM_PRIORITY:5
2)如何获取和设置当前线程优先级
getPriority():获取当前线程优先级
setProority(int p):设置当前线程优先级
高优先级线程要抢占低优先级线程cpu执行权。但是只是从概率上讲。

3.生命周期

线程生命周期.png

yield()

4.线程通信

方法

1)wait():使得调用wait()的线程进入阻塞状态,并释放同步监视器
2)notify():一旦执行此方法,就会唤醒被wait的一个线程。如果多个线程被wait,唤醒优先级高的
3)notifyAll():一旦执行此方法,就会唤醒被wait的所有线程

说明

1)wait(),notiry(),notiryAll()需要声明在同步代码块或者同步代码方法中
2)wait(),notiry(),notiryAll()调用者必须是同步代码块或者同步代码方法的同步监视器,否则会出现异常
3)wait(),notiry(),notiryAll()声明在java.lang.Object当中

sleep() VS wait()

总结

三、线程同步机制

1.同步代码块

synchronized(同步监视器){
      //需要同步的代码
}

同步监视器:类的对象
要求:多个线程必须要共用同一把锁,可以考虑使用this,类.class等

2.同步方法

synchronized添加到方法
synchronized method():同步监视器是this
static synchronized method():同步监视器是类.class

3.Lock锁 --- JDK5.0新增

class A {
    //1.实例化ReentrantLock对象
    private final ReenTrantLock lock = new ReenTrantLook();
    public void m (){
        lock.lock//2.先加锁
        try{
            //保证线程同步的代码
        }finally{
            lock.unlock();//3.后解锁
        }
    }
}

//注意:如果同步代码块有异常,要将unlock()写入finally语句块中
上一篇下一篇

猜你喜欢

热点阅读