让线程顺序执行代码

方法一:顺序在线程中创建实例

public class TestTwo {
    
    static TestTwo t=new TestTwo();
    class T1 extends Thread{
        @Override
        public void run() {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //T1线程中要处理的东西
            System.out.println("T1线程执行");
        }
    }

    class T2 extends Thread{
        @Override
        public void run() {
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //T2线程中要处理的东西
            System.out.println("T2线程执行");
            t.new T1().start();
        }
    }

    class T3 extends Thread{
        @Override
        public void run() {
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //T3线程中要处理的东西
            System.out.println("T3线程执行");
            t.new T2().start();
        }
    }

    public static void main(String[] args) {
        t.new T3().start();
    }

}

方法二:

参考:https://blog.csdn.net/eene894777/article/details/74942485

newSingleThreadExecutor()
这是一个单线程的Executor,它创建单个工作线程来执行任务,如果这个线程异常结束,会创建一个新的来替代它;它的特点是能确保依照任务在队列中的顺序来串行执行

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");
        // 执行方法一、线程不会顺序执行
//        t1.start();
//        t2.start();
//        t3.start();

        // 执行方法二、使用单个任务的线程池来实现、线程顺序执行
        ExecutorService executor = Executors.newSingleThreadExecutor();
        executor.submit(t1);
        executor.submit(t2);
        executor.submit(t3);
        executor.shutdown();
    }
}

 

posted @ 2019-10-09 17:04  唐胜伟  阅读(634)  评论(0编辑  收藏  举报