包含javaexcetor的词条

博主:adminadmin 2023-03-20 21:28:06 326

本篇文章给大家谈谈javaexcetor,以及对应的知识点,希望对各位有所帮助,不要忘了收藏本站喔。

本文目录一览:

Java 中对list 的编列,用List.iterator() 还是用for(int i=0;i

List的遍历方式有两种,第一种是采用for(int i = 0;ilist.size();i++),第二种采用list.iterator()。当List为ArrayList时两种方式遍历差别不大,第二种稍快。当List使用LinkedList时,用第一种速度非常慢,而采用第二种和ArrayList的遍历速度相当。

所以对于List建议采用iterator的方式进行遍历

补充:你用的是ArrayList,用LinkedList就是Iterator快,因为ArrayList随机的,而LinkedList是索引形式的.

为什么使用java 任务调度系统

Timer

相信大家都已经非常熟悉 java.util.Timer 了,它是最简单的一种实现任务调度的方法,下面给出一个具体的例子:

清单 1. 使用 Timer 进行任务调度

package com.ibm.scheduler;

import java.util.Timer;

import java.util.TimerTask;

public class TimerTest extends TimerTask {

private String jobName = "";

public TimerTest(String jobName) {

super();

this.jobName = jobName;

}

@Override

public void run() {

System.out.println("execute " + jobName);

}

public static void main(String[] args) {

Timer timer = new Timer();

long delay1 = 1 * 1000;

long period1 = 1000;

// 从现在开始 1 秒钟之后,每隔 1 秒钟执行一次 job1

timer.schedule(new TimerTest("job1"), delay1, period1);

long delay2 = 2 * 1000;

long period2 = 2000;

// 从现在开始 2 秒钟之后,每隔 2 秒钟执行一次 job2

timer.schedule(new TimerTest("job2"), delay2, period2);

}

}

Output:

execute job1

execute job1

execute job2

execute job1

execute job1

execute job2

使用 Timer 实现任务调度的核心类是 Timer 和 TimerTask。其中 Timer 负责设定 TimerTask 的起始与间隔执行时间。使用者只需要创建一个 TimerTask 的继承类,实现自己的 run 方法,然后将其丢给 Timer 去执行即可。

Timer 的设计核心是一个 TaskList 和一个 TaskThread。Timer 将接收到的任务丢到自己的 TaskList 中,TaskList 按照 Task 的最初执行时间进行排序。TimerThread 在创建 Timer 时会启动成为一个守护线程。这个线程会轮询所有任务,找到一个最近要执行的任务,然后休眠,当到达最近要执行任务的开始时间点,TimerThread 被唤醒并执行该任务。之后 TimerThread 更新最近一个要执行的任务,继续休眠。

Timer 的优点在于简单易用,但由于所有任务都是由同一个线程来调度,因此所有任务都是串行执行的,同一时间只能有一个任务在执行,前一个任务的延迟或异常都将会影响到之后的任务。

回页首

ScheduledExecutor

鉴于 Timer 的上述缺陷,Java 5 推出了基于线程池设计的 ScheduledExecutor。其设计思想是,每一个被调度的任务都会由线程池中一个线程去执行,因此任务是并发执行的,相互之间不会受到干扰。需要注意的是,只有当任务的执行时间到来时,ScheduedExecutor 才会真正启动一个线程,其余时间 ScheduledExecutor 都是在轮询任务的状态。

清单 2. 使用 ScheduledExecutor 进行任务调度

package com.ibm.scheduler;

import java.util.concurrent.Executors;

import java.util.concurrent.ScheduledExecutorService;

import java.util.concurrent.TimeUnit;

public class ScheduledExecutorTest implements Runnable {

private String jobName = "";

public ScheduledExecutorTest(String jobName) {

super();

this.jobName = jobName;

}

@Override

public void run() {

System.out.println("execute " + jobName);

}

public static void main(String[] args) {

ScheduledExecutorService service = Executors.newScheduledThreadPool(10);

long initialDelay1 = 1;

long period1 = 1;

// 从现在开始1秒钟之后,每隔1秒钟执行一次job1

service.scheduleAtFixedRate(

new ScheduledExecutorTest("job1"), initialDelay1,

period1, TimeUnit.SECONDS);

long initialDelay2 = 1;

long delay2 = 1;

// 从现在开始2秒钟之后,每隔2秒钟执行一次job2

service.scheduleWithFixedDelay(

new ScheduledExecutorTest("job2"), initialDelay2,

delay2, TimeUnit.SECONDS);

}

}

Output:

execute job1

execute job1

execute job2

execute job1

execute job1

execute job2

清单 2 展示了 ScheduledExecutorService 中两种最常用的调度方法 ScheduleAtFixedRate 和 ScheduleWithFixedDelay。ScheduleAtFixedRate 每次执行时间为上一次任务开始起向后推一个时间间隔,即每次执行时间为 :initialDelay, initialDelay+period, initialDelay+2*period, …;ScheduleWithFixedDelay 每次执行时间为上一次任务结束起向后推一个时间间隔,即每次执行时间为:initialDelay, initialDelay+executeTime+delay, initialDelay+2*executeTime+2*delay。由此可见,ScheduleAtFixedRate 是基于固定时间间隔进行任务调度,ScheduleWithFixedDelay 取决于每次任务执行的时间长短,是基于不固定时间间隔进行任务调度。

回页首

用 ScheduledExecutor 和 Calendar 实现复杂任务调度

Timer 和 ScheduledExecutor 都仅能提供基于开始时间与重复间隔的任务调度,不能胜任更加复杂的调度需求。比如,设置每星期二的 16:38:10 执行任务。该功能使用 Timer 和 ScheduledExecutor 都不能直接实现,但我们可以借助 Calendar 间接实现该功能。

清单 3. 使用 ScheduledExcetuor 和 Calendar 进行任务调度

package com.ibm.scheduler;

import java.util.Calendar;

import java.util.Date;

import java.util.TimerTask;

import java.util.concurrent.Executors;

import java.util.concurrent.ScheduledExecutorService;

import java.util.concurrent.TimeUnit;

public class ScheduledExceutorTest2 extends TimerTask {

private String jobName = "";

public ScheduledExceutorTest2(String jobName) {

super();

this.jobName = jobName;

}

@Override

public void run() {

System.out.println("Date = "+new Date()+", execute " + jobName);

}

/**

* 计算从当前时间currentDate开始,满足条件dayOfWeek, hourOfDay,

* minuteOfHour, secondOfMinite的最近时间

* @return

*/

public Calendar getEarliestDate(Calendar currentDate, int dayOfWeek,

int hourOfDay, int minuteOfHour, int secondOfMinite) {

//计算当前时间的WEEK_OF_YEAR,DAY_OF_WEEK, HOUR_OF_DAY, MINUTE,SECOND等各个字段值

int currentWeekOfYear = currentDate.get(Calendar.WEEK_OF_YEAR);

int currentDayOfWeek = currentDate.get(Calendar.DAY_OF_WEEK);

int currentHour = currentDate.get(Calendar.HOUR_OF_DAY);

int currentMinute = currentDate.get(Calendar.MINUTE);

int currentSecond = currentDate.get(Calendar.SECOND);

//如果输入条件中的dayOfWeek小于当前日期的dayOfWeek,则WEEK_OF_YEAR需要推迟一周

boolean weekLater = false;

if (dayOfWeek currentDayOfWeek) {

weekLater = true;

} else if (dayOfWeek == currentDayOfWeek) {

//当输入条件与当前日期的dayOfWeek相等时,如果输入条件中的

//hourOfDay小于当前日期的

//currentHour,则WEEK_OF_YEAR需要推迟一周

if (hourOfDay currentHour) {

weekLater = true;

} else if (hourOfDay == currentHour) {

//当输入条件与当前日期的dayOfWeek, hourOfDay相等时,

//如果输入条件中的minuteOfHour小于当前日期的

//currentMinute,则WEEK_OF_YEAR需要推迟一周

if (minuteOfHour currentMinute) {

weekLater = true;

} else if (minuteOfHour == currentSecond) {

//当输入条件与当前日期的dayOfWeek, hourOfDay,

//minuteOfHour相等时,如果输入条件中的

//secondOfMinite小于当前日期的currentSecond,

//则WEEK_OF_YEAR需要推迟一周

if (secondOfMinite currentSecond) {

weekLater = true;

}

}

}

}

if (weekLater) {

//设置当前日期中的WEEK_OF_YEAR为当前周推迟一周

currentDate.set(Calendar.WEEK_OF_YEAR, currentWeekOfYear + 1);

}

// 设置当前日期中的DAY_OF_WEEK,HOUR_OF_DAY,MINUTE,SECOND为输入条件中的值。

currentDate.set(Calendar.DAY_OF_WEEK, dayOfWeek);

currentDate.set(Calendar.HOUR_OF_DAY, hourOfDay);

currentDate.set(Calendar.MINUTE, minuteOfHour);

currentDate.set(Calendar.SECOND, secondOfMinite);

return currentDate;

}

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

ScheduledExceutorTest2 test = new ScheduledExceutorTest2("job1");

//获取当前时间

Calendar currentDate = Calendar.getInstance();

long currentDateLong = currentDate.getTime().getTime();

System.out.println("Current Date = " + currentDate.getTime().toString());

//计算满足条件的最近一次执行时间

Calendar earliestDate = test

.getEarliestDate(currentDate, 3, 16, 38, 10);

long earliestDateLong = earliestDate.getTime().getTime();

System.out.println("Earliest Date = "

+ earliestDate.getTime().toString());

//计算从当前时间到最近一次执行时间的时间间隔

long delay = earliestDateLong - currentDateLong;

//计算执行周期为一星期

long period = 7 * 24 * 60 * 60 * 1000;

ScheduledExecutorService service = Executors.newScheduledThreadPool(10);

//从现在开始delay毫秒之后,每隔一星期执行一次job1

service.scheduleAtFixedRate(test, delay, period,

TimeUnit.MILLISECONDS);

}

}

Output:

Current Date = Wed Feb 02 17:32:01 CST 2011

Earliest Date = Tue Feb 8 16:38:10 CST 2011

Date = Tue Feb 8 16:38:10 CST 2011, execute job1

Date = Tue Feb 15 16:38:10 CST 2011, execute job1

JAVA线程能创建线程吗

Java有三种创建线程的方式,分别是继承Thread类、实现Runable接口和使用线程池

1、继承Thread类

使用该方式创建及使用线程需按以下三个步骤:

(1)定义Thread类的子类,并重写父类的run()方法,方法里的内容就是线程所要执行的任务;

(2)创建子类的实例,即生成线程的实例对象;

(3)调用现成的start()方法来启动线程。

public class SubThread extends Thread {

private int ticket = 100; private String name; public ImplThread(String name) { this.name = name;

} public void run() { while (k 0){

System.out.println(ticket-- + "is saled by" + name);

} try{

sleep((int)Math.random() * 10);

}catch (InterruptedException e){

e.printStackTrace();

}

} public static void main (String []args){

SubThread t1 = new SubThread("A");

SubThread t2 = new SubThread("B");

t1.start();

t2.start();

}

}1234567891011121314151617181920212223

2、实现Runnable接口

(1)定义实现Runnable接口的实现类,并重写run()方法;

(2)创建Runnable接口实现类的实例,并将该实例作为参数传到Thread类的构造方法中来创建Thread对象,该Thread对象才是真正的线程对象;

(3)调用现成的start()方法来启动线程。

public class ImplThread implements Runnable {

private int ticket = 100; private String name; public ImplThread(String name) { this.name = name;

} public void run() { while (k 0){

System.out.println(ticket-- + "is saled by" + name);

} try{

sleep((int)Math.random() * 10);

}catch (InterruptedException e){

e.printStackTrace();

}

} public static void main (String []args){

ImplThread i1 = new ImplThread("A");

ImplThread i2 = new ImplThread("B");

Thread t1 = new Thread(i1);

Thread t2 = new Thread(i2);

t1.start();

t2.start();

}

}12345678910111213141516171819202122232425

上面这段代码跟继承Thread类的线程代码呈现的效果是一样的,虽然执行的是相同的代码,但彼此相互独立,且各自拥有自己的资源,互不干扰。

但是,在某些场景,我们希望各线程能共享资源,这时候就只能扩展Runnable接口了。

public class ImplThread implements Runnable {

private int ticket = 100; public void run() { while (k 0){

System.out.println(ticket-- + "is saled by" + Thread.currentThread());

} try{

sleep((int)Math.random() * 10);

}catch (InterruptedException e){

e.printStackTrace();

}

} public static void main (String []args){

ImplThread i = new ImplThread();

Thread t1 = new Thread(i);

Thread t2 = new Thread(i);

t1.start();

t2.start();

}

}1234567891011121314151617181920

这时候,线程t1和t2共享这100张票。

3、使用线程池

使用线程池并不是创建线程,而是对线程进行管理。Excetor为线程池超级接口,该接口中定义了一个execute(Runnable command)方法,用来执行传递过来的线程,ExecutorService就是我们所说的线程池,它继承了Excetor接口。如何创建线程池呢?Java提供了Executors类,该类有四个静态方法分别可以创建不同类型的线程池(ExecutorService)。

Executors.newCachedThreadPool() 创建可变大小的线程池

Executors.newFixedThreadPool(int number) 创建固定大小的线程池

Executors.newSingleThreadPool() 创建单任务线程池

Executors.newScheduledThreadPool(int number) 创建延迟线程池

import java.util.concurrent.Executors;

import java.util.concurrent.ExecutorService;

public class Test { public static void main(String[] args) {

//创建一个可重用固定线程数的线程池 ExecutorService pool = Executors.newFixedThreadPool(2);

//创建实现了Runnable接口对象,Thread对象当然也实现了Runnable接口 Thread t1 = new MyThread();

Thread t2 = new MyThread();

Thread t3 = new MyThread();

Thread t4 = new MyThread();

Thread t5 = new MyThread();

//将线程放入池中进行执行 pool.execute(t1);

pool.execute(t2);

pool.execute(t3);

pool.execute(t4);

pool.execute(t5);

//关闭线程池 pool.shutdown();

}

}

class MyThread extends Thread{ @Override

public void run() {

System.out.println(Thread.currentThread().getName()+"正在执行。。。");

}

} 12345678910111213141516171819202122232425262728

输出:

pool-1-thread-1正在执行。。。

pool-1-thread-1正在执行。。。

pool-1-thread-1正在执行。。。

pool-1-thread-1正在执行。。。

pool-1-thread-2正在执行。。。

Process finished with exit code 0

可见,线程得到了重用,线程池里只有两个线程在执行。

关于javaexcetor和的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站。