【Java面试】确保线程顺序执行的实现方法

简介: 【Java面试】确保线程顺序执行的实现方法

1.Thread.join()

我们来看看在 Java 7 Concurrency Cookbook 中相关的描述(很清楚地说明了 join() 的作用):

Waiting for the finalization of a thread
In some situations, we will have to wait for the finalization of a thread. For example, we may have a program that will begin initializing the resources it needs before proceeding with the rest of the execution. We can run the initialization tasks as threads and wait for its finalization before continuing with the rest of the program. For this purpose, we can use the join() method of the Thread class. When we call this method using a thread object, it suspends the execution of the calling thread until the object called finishes its execution.
当我们调用某个线程的这个方法时,这个方法会挂起调用线程,直到被调用线程结束执行,调用线程才会继续执行。内部使用了wait方法,和sleep的区别是,sleep不会释放锁,而wait会释放锁。
public class Main {
    public static void main(String[] args) throws InterruptedException {
        Thread thread1 = new Thread(new Runnable() {

            @Override
            public void run() {
                System.out
                        .println(Thread.currentThread().getId() + "running...");
            }
        });

        Thread thread2 = new Thread(new Runnable() {

            @Override
            public void run() {
                System.out
                        .println(Thread.currentThread().getId() + "running...");
            }
        });

        Thread thread3 = new Thread(new Runnable() {

            @Override
            public void run() {
                System.out
                        .println(Thread.currentThread().getId() + "running...");
            }
        });
        thread1.start();
        thread1.join();

        thread2.start();
        thread2.join();

        thread3.start();
        thread3.join();
        System.out.println("Main Thread exit!");
    }
}

主线程这种按照顺序调用了thread1、thread2、thread3,main thread存当了调用者的角色。

2.自定义实现串行执行器

import java.util.ArrayDeque;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Main {
    public static void main(String[] args) {
        Thread thread1 = new Thread(new Runnable() {

            @Override
            public void run() {
                System.out
                        .println(Thread.currentThread().getId() + "running...");
            }
        });

        Thread thread2 = new Thread(new Runnable() {

            @Override
            public void run() {
                System.out
                        .println(Thread.currentThread().getId() + "running...");
            }
        });

        Thread thread3 = new Thread(new Runnable() {

            @Override
            public void run() {
                System.out
                        .println(Thread.currentThread().getId() + "running...");
            }
        });

        SerialDefineExecutor defineExecutor = new SerialDefineExecutor();
        defineExecutor.execute(thread1);
        defineExecutor.execute(thread2);
        defineExecutor.execute(thread3);

        System.out.println("Main Thread exit!");
    }

    public static class SerialDefineExecutor implements Executor {
        ArrayDeque<Runnable> queue = new ArrayDeque<Runnable>();
        Runnable current = null;
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 10, 5,
                TimeUnit.SECONDS, sPoolWorkQueue);
        private static final BlockingQueue<Runnable> sPoolWorkQueue = new LinkedBlockingQueue<Runnable>(
                128);

        public SerialDefineExecutor() {
            threadPoolExecutor.allowCoreThreadTimeOut(true);
        }
        public synchronized void execute(Runnable runnable) {
            queue.offer(new Runnable() {

                @Override
                public void run() {
                    try {
                        runnable.run();
                    } finally {
                        next();
                    }
                }
            });
            if (current == null) {
                next();
            }
        }

        private synchronized void next() {
            if (!queue.isEmpty()) {
                current = queue.pop();
                threadPoolExecutor.execute(current);
            }
        }
    }
}

看过AsyncTask源码的各位,肯定看到过内部有这个串行执行器,保证内部线程的顺序执行,这里我们可以模仿写一个。

3.Thread.setPriority

设置线程优先级

public class Main {
    public static void main(String[] args) {
        Thread thread1 = new Thread(new Runnable() {

            @Override
            public void run() {
                System.out
                        .println(Thread.currentThread().getId() + "running...");
            }
        });

        Thread thread2 = new Thread(new Runnable() {

            @Override
            public void run() {
                System.out
                        .println(Thread.currentThread().getId() + "running...");
            }
        });

        Thread thread3 = new Thread(new Runnable() {

            @Override
            public void run() {
                System.out
                        .println(Thread.currentThread().getId() + "running...");
            }
        });

        thread1.setPriority(1);
        thread2.setPriority(2);
        thread3.setPriority(3);
        thread1.start();
        thread2.start();
        thread3.start();
        System.out.println("Main Thread exit!");
    }
}
目录
相关文章
|
2月前
|
安全 算法 Java
Java 多线程:线程安全与同步控制的深度解析
本文介绍了 Java 多线程开发的关键技术,涵盖线程的创建与启动、线程安全问题及其解决方案,包括 synchronized 关键字、原子类和线程间通信机制。通过示例代码讲解了多线程编程中的常见问题与优化方法,帮助开发者提升程序性能与稳定性。
110 0
|
2月前
|
Java API 调度
从阻塞到畅通:Java虚拟线程开启并发新纪元
从阻塞到畅通:Java虚拟线程开启并发新纪元
269 83
|
3月前
|
存储 SQL 安全
Java 无锁方式实现高性能线程实战操作指南
本文深入探讨了现代高并发Java应用中单例模式的实现方式,分析了传统单例(如DCL)的局限性,并提出了多种无锁实现方案。包括基于ThreadLocal的延迟初始化、VarHandle原子操作、Record不可变对象、响应式编程(Reactor)以及CDI依赖注入等实现方式。每种方案均附有代码示例及适用场景,同时通过JMH性能测试对比各实现的优劣。最后,结合实际案例设计了一个高性能配置中心,展示了无锁单例在实际开发中的应用。总结中提出根据场景选择合适的实现方式,并遵循现代单例设计原则以优化性能和安全性。文中还提供了代码获取链接,便于读者实践与学习。
82 0
|
2月前
|
存储 Java 调度
Java虚拟线程:轻量级并发的革命性突破
Java虚拟线程:轻量级并发的革命性突破
214 83
|
3月前
|
存储 Java
说一说 JAVA 内存模型与线程
我是小假 期待与你的下一次相遇 ~
|
3月前
|
移动开发 Java
说一说 Java 是如何实现线程间通信
我是小假 期待与你的下一次相遇 ~
|
存储 Java
【IO面试题 四】、介绍一下Java的序列化与反序列化
Java的序列化与反序列化允许对象通过实现Serializable接口转换成字节序列并存储或传输,之后可以通过ObjectInputStream和ObjectOutputStream的方法将这些字节序列恢复成对象。
|
10月前
|
存储 算法 Java
大厂面试高频:什么是自旋锁?Java 实现自旋锁的原理?
本文详解自旋锁的概念、优缺点、使用场景及Java实现。关注【mikechen的互联网架构】,10年+BAT架构经验倾囊相授。
大厂面试高频:什么是自旋锁?Java 实现自旋锁的原理?
|
10月前
|
存储 缓存 算法
面试官:单核 CPU 支持 Java 多线程吗?为什么?被问懵了!
本文介绍了多线程环境下的几个关键概念,包括时间片、超线程、上下文切换及其影响因素,以及线程调度的两种方式——抢占式调度和协同式调度。文章还讨论了减少上下文切换次数以提高多线程程序效率的方法,如无锁并发编程、使用CAS算法等,并提出了合理的线程数量配置策略,以平衡CPU利用率和线程切换开销。
面试官:单核 CPU 支持 Java 多线程吗?为什么?被问懵了!