多线程

发布时间 2023-11-20 14:51:21作者: 于辰文

多线程

创建线程的方法

  1. 继承Thread类,重写run方法,线程启动调用start方法

    class MThread extends Thread {
        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {
                if (i % 2 == 0) {
                    System.out.println(Thread.currentThread().getName() + ":" + i);
                }
            }
        }
    }
    public class ThreadTest1 {
        public static void main(String[] args) {
            MThread m1 = new MThread();
            m1.start();
            for (int i = 0; i < 100; i++) {
                if (i % 2 != 0) {
                    System.out.println(Thread.currentThread().getName() + ":" + i);
                }//main线程
            }
        }
    }
    
  2. 实现Runable接口,重写run方法,作为参数传入Thread对象,线程启动调用start方法

    class MRunnable implements Runnable {
        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {
                if (i % 2 == 0) {
                    System.out.println(Thread.currentThread().getName() + ":" + i);
                }
            }
        }
    }
    public class ThreadTest2 {
        public static void main(String[] args) {
            MRunnable mThread = new MRunnable();
            Thread thread = new Thread(mThread);
            thread.start();
            for (int i = 0; i < 100; i++) {
                if (i % 2 != 0) {
                    System.out.println(Thread.currentThread().getName() + ":" + i);
                }//main线程
            }
        }
    }
    
  3. 实现Callable接口,重写call方法,作为参数传入FutureTask对象,然后再作为参数传入Thread对象,线程启动调用start方法,可以使用FutureTask获取返回值

    class MCallable implements Callable<Integer> {
        @Override
        public Integer call() throws Exception {
            System.out.println("111111");
            return 1;
        }
    }
    public class ThreadTest3 {
        public static void main(String[] args) throws ExecutionException, InterruptedException {
            MCallable mc = new MCallable();
            FutureTask<Integer> ft = new FutureTask<>(mc);
            new Thread(ft, "t1").start();
            System.out.println(ft.isDone());//轮询
            System.out.println(ft.get());//阻塞
        }
    }
    
  4. 线程池

线程同步的方法

  1. synchronized:

    修饰方法 :

    修饰静态方法是给当前类加锁,会作用于类的所有对象实例 ,进入同步代码前要获得 当前 class 的锁

    修饰实例方法是给当前对象实例加锁,进入同步代码前要获得当前对象实例的锁

    修饰代码块:

    对括号里指定的对象/类加锁:

    • synchronized(object) 表示进入同步代码库前要获得 给定对象的锁
    • synchronized(类.class) 表示进入同步代码前要获得 给定 Class 的锁
  2. ReentrantLock:

    Lock lock = new ReentrantLock();
    new Thread(() -> {
        lock.lock();
        try {
           ......
        } catch (InterruptedException e) {
        	e.printStackTrace();
        } finally {
        	lock.unlock();
        }
    }, "t1").start();
    

​ 使用顺序推荐:ReentrantLock > synchronized 同步代码块 > synchronized 同步方法

参考资料