如何将不同的线程分配给不使用主主线程的其他类的不同方法

时间:2017-06-26 07:37:24

标签: java multithreading java-threads thread-synchronization

假设我有一个主要课程Start.java

public class Start{
    //Here I want to integrate the programs for which i will be needing threads
}

我还有两个类,它们包含两种不同的方法。

public class ReadUpdateDb {
    public void updateDb(Statement stmt) 
}

public class DbToXls {
    public void dbtoXLS(Statement stmt)
}

这是我的问题:我不知道如何为方法updateDb()dbtoXLS()分配两个不同的线程。

此外,我希望每两小时运行一次updateDb,一天dbtoXLS运行一次。

2 个答案:

答案 0 :(得分:1)

如上所述,ScheduledExecutorService将完成这项工作。我还建议使用Guava' ThreadFactoryBuilder来命名线程,将来调试会更容易。

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

public class Start {

    private static final Integer POOL_SIZE = 2;

    private final ScheduledExecutorService schedExecutor = Executors
                    .newScheduledThreadPool(POOL_SIZE,
                     new ThreadFactoryBuilder().setNameFormat("Schedule-Updater-%d")
                    .setDaemon(true).build());

    public void go() {
        Statement stmt = null;  // construct your statement here
        ReadUpdateDb readUpdateDb = new ReadUpdateDb();
        schedExecutor.scheduleAtFixedRate(() -> readUpdateDb.updateDb(stmt),
                          0, 2, TimeUnit.HOURS);
        DbToXls dbToXls = new DbToXls();
        schedExecutor.scheduleAtFixedRate(() -> dbToXls.dbtoXLS(stmt),
                          0, 1, TimeUnit.DAYS);
        schedExecutor.shutdown();
    }
}

希望它有所帮助!

答案 1 :(得分:0)

您可以使用ScheduledExecutorService或开源实施,例如quartz。

ScheduledExecutorService示例,每15分钟运行一次。

private final ScheduledExecutorService scheduler = Executors
        .newScheduledThreadPool(1);

    public void startScheduleTask() {

    final ScheduledFuture<?> taskHandle = scheduler.scheduleAtFixedRate(
        new Runnable() {
            public void run() {
                try {
                    updateDb();
                }catch(Exception ex) {
                    ex.printStackTrace(); //or loggger would be better
                }
            }
        }, 0, 15, TimeUnit.MINUTES);
    }

QUARTZ示例

public class SimpleTriggerExample {
    public static void main(String[] args) throws Exception {

        // Quartz 1.6.3
        // JobDetail job = new JobDetail();
        // job.setName("dummyJobName");
        // job.setJobClass(HelloJob.class);

        JobDetail job = JobBuilder.newJob(HelloJob.class)
            .withIdentity("dummyJobName", "group1").build();

                //Quartz 1.6.3
        // SimpleTrigger trigger = new SimpleTrigger();
        // trigger.setStartTime(new Date(System.currentTimeMillis() + 1000));
        // trigger.setRepeatCount(SimpleTrigger.REPEAT_INDEFINITELY);
        // trigger.setRepeatInterval(30000);

        // Trigger the job to run on the next round minute
        Trigger trigger = TriggerBuilder
            .newTrigger()
            .withIdentity("dummyTriggerName", "group1")
            .withSchedule(
                SimpleScheduleBuilder.simpleSchedule()
                    .withIntervalInSeconds(5).repeatForever())
            .build();

        //job2
        JobDetail job1 = JobBuilder.newJob(HelloJob2.class)
                .withIdentity("dummyJobName1", "group1").build();
        Trigger trigger1 = TriggerBuilder
                .newTrigger()
                .withIdentity("dummyTriggerName1", "group1")
                .withSchedule(
                    SimpleScheduleBuilder.simpleSchedule()
                        .withIntervalInSeconds(5).repeatForever())
                .build();
        // schedule it
        Scheduler scheduler = new StdSchedulerFactory().getScheduler();
        scheduler.start();
        scheduler.scheduleJob(job, trigger);
        //scheduler.scheduleJob(job1, trigger1);

    }
}