Java 指定线程执行顺序(三种方式)其实是四种

摘要:
=1){wait();}for(inti=0;i˂2;i++){System.out.println("AAAAA");}orderNum=2;notifyAll();}catch(InterruptedExceptione){e.printStackTrace();}}publicsynchronizedvoidmethodB(){try{while(orderNum!

转载:https://blog.csdn.net/eene894777/article/details/74942485

方法一:通过共享对象锁加上可见变量来实现。

public classMyService {
 
    private volatile int orderNum = 1;
 
    public synchronized voidmethodA() {
        try{
            while (orderNum != 1) {
                wait();
            }
            for (int i = 0; i < 2; i++) {
                System.out.println("AAAAA");
            }
            orderNum = 2;
            notifyAll();
        } catch(InterruptedException e) {
            e.printStackTrace();
        }
    }
 
    public synchronized voidmethodB() {
        try{
            while (orderNum != 2) {
                wait();
            }
            for (int i = 0; i < 2; i++) {
                System.out.println("BBBBB");
            }
            orderNum = 3;
            notifyAll();
        } catch(InterruptedException e) {
            e.printStackTrace();
        }
    }
 
    public synchronized voidmethodC() {
        try{
            while (orderNum != 3) {
                wait();
            }
            for (int i = 0; i < 2; i++) {
                System.out.println("CCCCC");
            }
            orderNum = 1;
            notifyAll();
        } catch(InterruptedException e) {
            e.printStackTrace();
        }
    }
}
 
importservice.MyService;
public class ThreadAA extendsThread {
 
    privateMyService dbtools;
 
    publicThreadAA(MyService dbtools) {
        super();
        this.dbtools =dbtools;
    }
 
    @Override
    public voidrun() {
        dbtools.methodA();
    }
 
}
importservice.MyService;
public class ThreadBB extendsThread {
 
    privateMyService dbtools;
 
    publicThreadBB(MyService dbtools) {
        super();
        this.dbtools =dbtools;
    }
 
    @Override
    public voidrun() {
        dbtools.methodB();
    }
 
}
importservice.MyService;
public class ThreadCC extendsThread {
 
    privateMyService dbtools;
 
    publicThreadCC(MyService dbtools) {
        this.dbtools =dbtools;
    }
 
    @Override
    public voidrun() {
        dbtools.methodC();
    }
 
}
importextthread.ThreadCC;
importservice.MyService;
importextthread.ThreadAA;
importextthread.ThreadBB;
 
public classRun {
 
    public static voidmain(String[] args) {
        MyService myService = newMyService();
        for (int i = 0; i < 2; i++) {
            ThreadBB output = newThreadBB(myService);
            output.start();
            ThreadAA input = newThreadAA(myService);
            input.start();
            ThreadCC threadCC = newThreadCC(myService);
            threadCC.start();
        }
    }
 
}

方法二:通过主线程Join()

class T11 extendsThread {
    public voidrun() {
        System.out.println("in T1");
    }
}
 
class T22 extendsThread {
    public voidrun() {
        System.out.println("in T2");
    }
}
 
class T33 extendsThread {
    public voidrun() {
        System.out.println("in T3");
    }
}
 
public classTest2 {
    public static void main(String[] args) throwsInterruptedException {
        T11 t1 = newT11();
        T22 t2 = newT22();
        T33 t3 = newT33();
        t1.start();
        t1.join();
        t2.start();
        t2.join();
        t3.start();
    }
}

方法三:通过线程执行时Join()

class T1 extendsThread {
    public voidrun(){
        Random random = newRandom();
        try{
            Thread.sleep(random.nextInt(1000));
        } catch(InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("in T1");
    }
}
 
class T2 extendsThread{
    privateThread thread;
    publicT2(Thread thread) {
        this.thread =thread;
    }
 
    public voidrun(){
        try{
            thread.join();
        } catch(InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("in T2");
    }
}
 
class T3 extendsThread{
    privateThread thread;
    publicT3(Thread thread) {
        this.thread =thread;
    }
 
    public voidrun(){
        try{
            thread.join();
        } catch(InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("in T3");
    }
}
 
public classTest {
    public static void main(String[] args) throwsInterruptedException {
        T1 t1 = newT1();
        T2 t2 = newT2(t1);
        T3 t3 = newT3(t2);
        t2.start();
        t1.start();
        t3.start();
    }
}

方法四,使用线程池newSingleThreadExecutor()

packagecom.zyh.controller.test;

importjava.util.concurrent.ExecutorService;
importjava.util.concurrent.Executors;

/*** student threads
 *
 * @author1101399
 * @CreateDate 2018-7-30 下午2:09:01
 */
public classThreadTestOne {

    public static void main(String[] args) throwsInterruptedException {
        final ThreadTest A1 = new ThreadTest("A1");
        final ThreadTest A2 = new ThreadTest("A2");
        final ThreadTest A3 = new ThreadTest("A3");
        // A1.start(); TODO 屏蔽
        // A2.start(); TODO 屏蔽
        A1.join();
        A2.join();
        System.out.println("方法一实现多线程");
        if (!A1.isAlive()) {//A1 线程不存在的时候控制台打印一条信息
            System.out.println("A1执行完毕?!");
        }

        final Thread B1 = new Thread(new RunnableTest("B1"));
        // B1.start(); TODO 屏蔽
        final Thread B2 = new Thread(new RunnableTest("B2"));
        // B2.start(); TODO 屏蔽
        B1.join();
        B2.join();
        System.out.println("方法二实现多线程");

        /*** 直接实现线程的开辟 FIXME
         */
        final Thread C1 = new Thread(newRunnable() {
            @Override
            public voidrun() {
                try{
                    A1.join();
                    A2.join();
                    B1.join();
                    B2.join();
                } catch(InterruptedException e) {
                    e.printStackTrace();
                }
                for (int i = 0; i < 15; i++) {
                    System.out.println("··············");
                }
            }

        });
        // C1.start(); TODO 屏蔽
        C1.join();
        System.out.println("方法三实现多线程");


        System.out.println("线程池的应用");
        //线程池的学习&应用 TODO 依次执行
        ExecutorService executor =Executors.newSingleThreadExecutor();
        executor.submit(A1);
        executor.submit(A2);
        executor.submit(A3);
        executor.execute(B1);//这种样子的线程类就是不执行
executor.execute(A1);
        executor.submit(B1);// 这三种线程的实现方式之前不能 XXX start()启动线程
        executor.submit(B2);// 这三种线程的实现方式之前不能 XXX start()启动线程
        executor.submit(C1);// 这三种线程的实现方式之前不能 XXX start()启动线程
executor.shutdown();//停止传入任务

        //executor.shutdownNow();//停止线程池-对线程池说STOP
        //会导致线程池中第一个线程的sleep出现sleep interrupted异常
        //该函数的核心是:它向该线程发起interrupt()请求,而sleep()方法遇到有interrupt()请求时,会抛出InterruptedException(),并继续往下执行
        //运行到这条语句直接停止线程池-检测线程停止后执行的join()函数毫无意义,不能生效
}

    /*** 继承Thread来实现多线程编程 FIXME
     */
    public static class ThreadTest extendsThread {
        publicString nameOne;
        publicStringBuffer nameTwo;
        publicStringBuilder nameThree;
        private longtime;

        //构造函数
        publicThreadTest(String name) {
            this.nameOne =name;
        }

        //构造函数
        public ThreadTest(String name, longtime) {
            this.nameOne =name;
            this.time =time;
        }

        @Override
        public voidrun() {
            for (int i = 0; i < 5; i++) {
                System.out.println(this.nameOne + " Thread运行第 " + i + " 次!");
                try{
                    if (this.time != 0) {
                        sleep(this.time +i);
                        System.out.println(this.nameOne + "-time-" + (time +i));
                    } else{
                        //sleep((int) Math.random() * 1000);
                        sleep(50);
                        System.out
                                .println(this.nameOne + "-random-" + (int) (Math.random() * 1000));
                    }
                } catch(InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /*** 实现接口Runnable来实现多线程编程 FIXME
     */
    public static class RunnableTest implementsRunnable {

        publicString nameOne;
        publicStringBuffer nameTwo;
        publicStringBuilder nameThree;
        private longtime;

        publicRunnableTest(String name) {
            this.nameOne =name;
        }

        public RunnableTest(String name, longtime) {
            this.nameOne =name;
            this.time =time;
        }

        @Override
        public voidrun() {
            for (int i = 0; i < 5; i++) {
                System.out.println(this.nameOne + " Runnable运行第 " + i + " 次!");
                try{
                    if (this.time != 0) {
                        Thread.sleep(this.time +i);
                        System.out.println(this.nameOne + "-time-" + (time +i));
                    } else{
                        Thread.sleep((int) Math.random() * 1000);
                        System.out
                                .println(this.nameOne + "-random-" + (int) (Math.random() * 1000));
                    }
                } catch(InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

    }

}
newSingleThreadExecutor()单线程化线程池
      final Thread B1 = new Thread(new RunnableTest("B1"));
        B1.start();//TODO 屏蔽
        final Thread B2 = new Thread(new RunnableTest("B2"));
        B2.start();//TODO 屏蔽

final Thread C1 = new Thread(newRunnable() {
            @Override
            public voidrun() {
                try{
                    A1.join();
                    A2.join();
                    B1.join();
                    B2.join();
                } catch(InterruptedException e) {
                    e.printStackTrace();
                }
                for (int i = 0; i < 2; i++) {
                    System.out.println("··············");
                }
            }

        });
        C1.start();//TODO 屏蔽

        executor.submit(B1);//这三种线程的实现方式之前不能 XXX start()启动线程
        executor.submit(B2);//这三种线程的实现方式之前不能 XXX start()启动线程
        executor.submit(C1);//这三种线程的实现方式之前不能 XXX start()启动线程

免责声明:文章转载自《Java 指定线程执行顺序(三种方式)其实是四种》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇jquery 判断元素是否存在于数组中抓取Web网页数据分析下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

【java开发系列】—— java输入输出流

前言   任何语言输入输出流都是很重要的部分,比如从一个文件读入内容,进行分析,或者输出到另一个文件等等,都需要文件流的操作。这里简单介绍下reader,wirter,inputstream,outputstream的使用方法。其实Apache commons里面有个方法IOUtils可是实现方便快捷的流拷贝,感兴趣的可以参考官方文档。   JAVA的...

android 随手记 读写文件的几种方式

java中多种方式读文件 一、多种方式读文件内容。 1、按字节读取文件内容 2、按字符读取文件内容 3、按行读取文件内容 4、随机读取文件内容 */ import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import ja...

java使用jdbc对sqlite 添加、删除、修改的操作

package com.jb.jubmis.Dao.DaoImpl; import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import...

菜鸟学JDBC(二)

  上一篇文章( http://blog.csdn.net/rowandjj/article/details/8883383)我们了解了如何通过JDBC连接mysql数据库,并通过一个简单的代码示例演示了具体的操作,这里简单回顾一下流程: 1.装载驱动(Class.forName()....); 2.通过DriverManager类与数据库建立连接(Con...

Java并发编程之异步Future机制的原理和实现

项目中经常有些任务需要异步(提交到线程池中)去执行,而主线程往往需要知道异步执行产生的结果,这时我们要怎么做呢?用runnable是无法实现的,我们需要用callable看下面的代码: Java代码   import java.util.concurrent.Callable;   import java.util.concurrent.Execut...

转载 Android之网络与通信

2.三种网络接口简述2.1标准Java接口java.net.*提供与联网有关的类,包括流和数据包套接字、Internet协议、常见HTTP处理。使用java.net.*包连接网络代码:Java代码 收藏代码try{ //定义地址 URL url=newURL("http://www.google.com"); //打开连接 HttpURLConn...