三个线程依次顺序执行

保证三个线程依次按顺序执行

在有一些需求的情况下,我们需要三个线程依次按顺序执行,那么有人就会问了,为什么不把三个线程的run方法依次放到三个方法体中,然后依次执行,按顺序调用三个方法体,这样不是同样达到了目的了么,为什么非要弄的那么复杂,我个人的观点是别人面试官不问的这样深一点,怎么能体现他的技术了。所以我就在网上找了几篇blok,发现代码都有,不过都达不到目的,在这一篇blok中 [ 链接 ] 发现用到了join方法,不过经过测试,达不到想要的目的。废话不多说,下面贴代码

 final Thread t1 = new Thread(new Runnable() {
            public void run() {
                System.out.println(Thread.currentThread().getName() + " run 1");
            }
        }, "T1");
        final Thread t2 = new Thread(new Runnable() {
            public void run() {
                System.out.println(Thread.currentThread().getName() + " run 2");
                try {
                    t1.join(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "T2");
        final Thread t3 = new Thread(new Runnable() {
            public void run() {
                System.out.println(Thread.currentThread().getName() + " run 3");
                try {
                    t2.join(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "T3");
        t1.start();
        t2.start();
        t3.start();
        }

在这里我在t2的线程里面t1 的join方法,抢占时间片,然后在t3的线程里面,抢占t2的时间片,理应是 t3执行>t2执行>t1执行,可以到最后结果的时候,每次的结果都不尽相同,这让我很纳闷,有兴趣的同学可以尝试一下。欢迎互相讨论。

在这里我就去翻看线程的文档,发现了newSingleThreadExecutor 这个线程池,保证线程里面的任务依次执行,这让我发现了新大陆,立马实践了一下,发现不负所望

public class TestJoin {
    public static void main(String[] args) throws InterruptedException {
        final Thread t1 = new Thread(new Runnable() {
            public void run() {
                System.out.println(Thread.currentThread().getName() + " run 1");
            }
        }, "T1");
        final Thread t2 = new Thread(new Runnable() {
            public void run() {
                System.out.println(Thread.currentThread().getName() + " run 2");
                try {
                    t1.join(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "T2");
        final Thread t3 = new Thread(new Runnable() {
            public void run() {
                System.out.println(Thread.currentThread().getName() + " run 3");
                try {
                    t2.join(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "T3");
        // method1
        //t1.start();
        //t2.start();
        //t3.start();

//        method 2 使用 单个任务的线程池来实现。保证线程的依次执行
        ExecutorService executor = Executors.newSingleThreadExecutor();
        executor.submit(t1);
        executor.submit(t2);
        executor.submit(t3);
        executor.shutdown();
    }
}

在这里发现结果每次都是 t1执行,t2执行,t3执行,这里达到目的了之后,不禁回想,这个Single线程池为啥这么好用,不由得就像把线程池狠狠的看一遍,然后就去翻看了源代码

    /**
     * Creates an Executor that uses a single worker thread operating
     * off an unbounded queue. (Note however that if this single
     * thread terminates due to a failure during execution prior to
     * shutdown, a new one will take its place if needed to execute
     * subsequent tasks.)  Tasks are guaranteed to execute
     * sequentially, and no more than one task will be active at any
     * given time. Unlike the otherwise equivalent
     * {@code newFixedThreadPool(1)} the returned executor is
     * guaranteed not to be reconfigurable to use additional threads.
     *
     * @return the newly created single-threaded Executor
     */
    public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
    }

这个实例化的意思我尝试翻译了一下,意思就是创建一个只有一个线程的线程池来操作不限数量的队列,也就是把线程放进了一个队列中,队列我们都知道是FIFO的。SingleThreadExecutor的工作线程只有一个,其他队列中的线程都处于休眠,也就是sleep状态,当这个worker线程做完事了,也就是run方法运行结束,就又从队列中拿出一个休眠线程(sleep)出来唤醒(notify),这样依次把队列中的所有线程处理完毕,这样并没有结束,如果线程池中没有待处理的线程,线程池一直会等待,等待下一次任务的提交,除非把线程池给shutdown掉,这样线程池的生命周期才算完毕。

第一次写博客,希望大家多多关注,大家共同进步,我也瞻仰了许多大神写的博客,希望紧跟大神的脚步。
—小小程序员

  • 10
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 13
    评论
以下是一个简单的示例代码,演示如何按照顺序执行线程: ``` public class MainActivity extends AppCompatActivity { private TextView mTextView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTextView = findViewById(R.id.text_view); // 创建三个线程 Thread thread1 = new Thread(new MyRunnable("线程1")); Thread thread2 = new Thread(new MyRunnable("线程2")); Thread thread3 = new Thread(new MyRunnable("线程3")); // 依次启动三个线程 thread1.start(); try { thread1.join(); } catch (InterruptedException e) { e.printStackTrace(); } thread2.start(); try { thread2.join(); } catch (InterruptedException e) { e.printStackTrace(); } thread3.start(); try { thread3.join(); } catch (InterruptedException e) { e.printStackTrace(); } } private class MyRunnable implements Runnable { private String mName; public MyRunnable(String name) { mName = name; } @Override public void run() { // 在这里编写线程的逻辑 for (int i = 0; i < 5; i++) { final String text = mName + "执行了第" + (i + 1) + "次"; runOnUiThread(new Runnable() { @Override public void run() { mTextView.append(text + "\n"); } }); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } } ``` 这个示例代码中,我们创建了三个线程,分别执行了一些简单的逻辑。在 `onCreate` 方法中,我们依次启动了这三个线程,并使用 `join` 方法等待每个线程执行完毕。这样,就可以保证这三个线程按照顺序执行
评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值