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

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

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

public class MyService {
 
    private volatile int orderNum = 1;
 
    public synchronized void methodA() {
        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 void methodB() {
        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 void methodC() {
        try {
            while (orderNum != 3) {
                wait();
            }
            for (int i = 0; i < 2; i++) {
                System.out.println("CCCCC");
            }
            orderNum = 1;
            notifyAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
 
import service.MyService;
public class ThreadAA extends Thread {
 
    private MyService dbtools;
 
    public ThreadAA(MyService dbtools) {
        super();
        this.dbtools = dbtools;
    }
 
    @Override
    public void run() {
        dbtools.methodA();
    }
 
}
import service.MyService;
public class ThreadBB extends Thread {
 
    private MyService dbtools;
 
    public ThreadBB(MyService dbtools) {
        super();
        this.dbtools = dbtools;
    }
 
    @Override
    public void run() {
        dbtools.methodB();
    }
 
}
import service.MyService;
public class ThreadCC extends Thread {
 
    private MyService dbtools;
 
    public ThreadCC(MyService dbtools) {
        this.dbtools = dbtools;
    }
 
    @Override
    public void run() {
        dbtools.methodC();
    }
 
}
import extthread.ThreadCC;
import service.MyService;
import extthread.ThreadAA;
import extthread.ThreadBB;
 
public class Run {
 
    public static void main(String[] args) {
        MyService myService = new MyService();
        for (int i = 0; i < 2; i++) {
            ThreadBB output = new ThreadBB(myService);
            output.start();
            ThreadAA input = new ThreadAA(myService);
            input.start();
            ThreadCC threadCC = new ThreadCC(myService);
            threadCC.start();
        }
    }
 
}

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

class T11 extends Thread {
    public void run() {
        System.out.println("in T1");
    }
}
 
class T22 extends Thread {
    public void run() {
        System.out.println("in T2");
    }
}
 
class T33 extends Thread {
    public void run() {
        System.out.println("in T3");
    }
}
 
public class Test2 {
    public static void main(String[] args) throws InterruptedException {
        T11 t1 = new T11();
        T22 t2 = new T22();
        T33 t3 = new T33();
        t1.start();
        t1.join();
        t2.start();
        t2.join();
        t3.start();
    }
}

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

class T1 extends Thread {
    public void run(){
        Random random = new Random();
        try {
            Thread.sleep(random.nextInt(1000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("in T1");
    }
}
 
class T2 extends Thread{
    private Thread thread;
    public T2(Thread thread) {
        this.thread = thread;
    }
 
    public void run(){
        try {
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("in T2");
    }
}
 
class T3 extends Thread{
    private Thread thread;
    public T3(Thread thread) {
        this.thread = thread;
    }
 
    public void run(){
        try {
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("in T3");
    }
}
 
public class Test {
    public static void main(String[] args) throws InterruptedException {
        T1 t1 = new T1();
        T2 t2 = new T2(t1);
        T3 t3 = new T3(t2);
        t2.start();
        t1.start();
        t3.start();
    }
}

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

package com.zyh.controller.test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * student threads
 *
 * @author 1101399
 * @CreateDate 2018-7-30 下午2:09:01
 */
public class ThreadTestOne {

    public static void main(String[] args) throws InterruptedException {
        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(new Runnable() {
            @Override
            public void run() {
                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 extends Thread {
        public String nameOne;
        public StringBuffer nameTwo;
        public StringBuilder nameThree;
        private long time;

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

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

        @Override
        public void run() {
            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 implements Runnable {

        public String nameOne;
        public StringBuffer nameTwo;
        public StringBuilder nameThree;
        private long time;

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

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

        @Override
        public void run() {
            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(new Runnable() {
            @Override
            public void run() {
                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()启动线程

 

转载于:https://www.cnblogs.com/supperlhg/p/9391482.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 可以使用Java中的多线程技术来执行SQL语句。 可以使用Java中的JDBC API来执行SQL语句,并且通过创建多个线程并行执行SQL语句来提高执行效率。 不过,请注意在多线程环境中使用JDBC时需要特别注意线程安全性问题。因为JDBC API并不是线程安全的,因此需要通过特殊的方式来解决这个问题。 推荐使用数据库连接池,在每个线程中使用单独的数据库连接来执行SQL语句。这样可以保证线程安全并且提高执行效率。 ### 回答2: Java中可以使用多线执行SQL语句的方式有几种。 一种是通过多线程调用JDBC(Java Database Connectivity)来执行SQL语句。JDBC是Java提供的用于与数据库进行连接和操作的API,可以通过多线程创建多个数据库连接,并使用不同的线执行SQL语句。这种方式需要考虑线程安全的问题,可以通过使用锁或者连接池等机制来解决。 另一种方式是通过使用线程池来执行SQL语句。Java中提供了线程池的机制,可以通过创建线程池来管理多个线程的执行,将SQL语句封装成任务提交给线程池,线程池会自动分配线执行任务。这种方式可以有效地利用线程资源,提高程序的执行效率。 还可以使用并发控制工具来执行SQL语句,如使用CountDownLatch或CyclicBarrier等工具控制多个线程同时执行SQL语句,或者使用Semaphore来控制并发执行线程数量。这种方式可以根据需要灵活地控制并发执行线程数量,以及线程的执行顺序。 无论使用哪种方式,都需要注意线程安全的问题,避免多个线程同时访问和修改数据库的数据导致数据不一致的问题。可以使用事务或者加锁等机制来确保数据的一致性。此外,还需要考虑数据库的连接数限制和性能问题,根据实际情况合理配置连接池和线程池的大小,以及优化SQL语句的执行效率。 ### 回答3: 在Java中,可以使用多线执行SQL语句以提高数据库操作的效率。实现多线执行SQL语句可以通过以下步骤: 1. 创建数据库连接池:使用数据库连接池可以复用连接,减少连接数据库的开销。常见的数据库连接池有HikariCP、Druid等,可以根据需求选择合适的连接池。 2. 创建线程池:使用线程池可以管理线程的创建和销毁,提高线程的复用性。可以通过Java提供的Executors类创建线程池,指定线程数量等参数。 3. 创建Runnable任务:将要执行的SQL语句封装为Runnable任务,每个任务负责执行一条SQL语句。可以使用JDBC连接数据库,并使用Connection对象执行SQL语句,处理查询结果等。 4. 提交任务给线程池:将创建的Runnable任务提交给线程池执行线程池会自动从线程池中获取一个线程来执行任务。 5. 获取执行结果:可以通过Future对象来获取每个任务的执行结果。在提交任务时,会返回一个Future对象,可以通过该对象的方法获取任务的执行状态和结果。 6. 关闭线程池和数据库连接池:在多线执行SQL语句完成后,需要及时关闭线程池和数据库连接池,释放资源。 需要注意的是,在多线执行SQL语句时,需要考虑线程安全和事务管理。可以通过加锁、使用事务等技术来保证数据的一致性和线程的安全性。 总而言之,通过使用数据库连接池和线程池,以及合适的多线程编程技术,可以在Java中实现多线执行SQL语句,提高数据库操作的效率和性能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值