导航:首页 > 编程语言 > javatask

javatask

发布时间:2025-02-24 19:26:22

① 用java实现每隔10s向数据库添加一条记录,记录为时间和日期

1、在spring.xml文件中(有的也叫applicationContext.xml)中添加如下:

<context:annotation-config/>
<beanclass="org.springframework.beans.factory.annotation."/>
<context:component-scanbase-package="com.demo.init.task"/>
<!--base-package="com.demo.init.task"是ScheledExcuteTask类所在的包-->

5、启动服务器即可!

② java中Time和TimeTask的使用

代码如下:
public class MusicTitle {
String title ="Notitle.";
String artist="No artist.";
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getArtist() {
return artist;
}
public void setArtist(String artist) {
this.artist = artist;
}

}

public class MusicStore {
String owner="Noowner.";
int openTime =0;
int closeTime=0;
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public void setOpen(int openTime){
this.openTime=openTime;
}
public int getOpen(){
return openTime;
}
public void setClose(int closeTime){
this.closeTime=closeTime;
}
public int getClose(){
return closeTime;
}
public boolean isOpen(){
AltDate AltDate=new AltDate();
int nowtime = AltDate.getHourInt() ;
if(nowtime>=this.getOpen() && nowtime<=this.getClose()){
return true;
}
else{
return false;
}
}
public String getOpenClosedMessage(){
if(isOpen()){
return "We're Open!";

}else{
return "We're Closed!";
}
}
public void displayHoursOfOperation(){
System.out.println("StoreHours:");
System.out.println("Daily:"+this.getOpen()+":00 AM-"+this.getClose()+":00 PM");
}
public String toString(){
return "Owneris:"+ getOwner();
}
MusicTitle[] title=null;
public MusicTitle[] getTitle() {
return title;
}
public void setTitle(MusicTitle[] title) {
this.title = title;
}
public void displayMusicTitles(){
for(int i=0;i<title.length;i++){
System.out.println("Title"+(i+1)+":");
System.out.println("Title:"+title[i].getTitle());
System.out.println("Artist:"+title[i].getArtist());
}
}

}

public class AltDate {

@SuppressWarnings("deprecation")
public int getHourInt(){
java.util.Date date=new java.util.Date();
return date.getHours();

}
}

import java.util.Scanner;

public class TestMusicStore {

/**
* @param args
*/
public static void main(String[] args) {
// TODO 自动生成的方法存根
MusicStore ms=new MusicStore() ;
Scanner in=new Scanner(System.in);
ms.setOwner(in.next());
ms.setOpen(in.nextInt());
ms.setClose(in.nextInt());
MusicTitle[] mt=new MusicTitle[2];
for(int i=0;i<2;i++){

mt[i].setTitle(in.next());
mt[i].setArtist(in.next());

}
ms.setTitle(mt);
ms.getOpenClosedMessage();
ms.displayHoursOfOperation();
System.out.println(ms.toString());
ms.displayMusicTitles();
System.exit(0);
}

}

③ java线程池怎么实现的

线程池简介:

多线程技术主要解决处理器单元内多个线程执行的问题,它可以显著减少处理器单元的闲置时间,增加处理器单元的吞吐能力。


假设一个服务器完成一项任务所需时间为:T1 创建线程时间,T2 在线程中执行任务的时间,T3 销毁线程时间。

如果:T1 + T3 远大于 T2,则可以采用线程池,以提高服务器性能。

一个线程池包括以下四个基本组成部分:

1、线程池管理器(ThreadPool):用于创建并管理线程池,包括 创建线程池,销毁线程池,添加新任务;

2、工作线程(PoolWorker):线程池中线程,在没有任务时处于等待状态,可以循环的执行任务;

3、任务接口(Task):每个任务必须实现的接口,以供工作线程调度任务的执行,它主要规定了任务的入口,任务执行完后的收尾工作,任务的执行状态等;

4、任务队列(taskQueue):用于存放没有处理的任务。提供一种缓冲机制。

线程池技术正是关注如何缩短或调整T1,T3时间的技术,从而提高服务器程序性能的。它把T1,T3分别安排在服务器程序的启动和结束的时间段或者一些空闲的时间段,这样在服务器程序处理客户请求时,不会有T1,T3的开销了。

线程池不仅调整T1,T3产生的时间段,而且它还显著减少了创建线程的数目,看一个例子:

假设一个服务器一天要处理50000个请求,并且每个请求需要一个单独的线程完成。在线程池中,线程数一般是固定的,所以产生线程总数不会超过线程池中线程的数目,而如果服务器不利用线程池来处理这些请求则线程总数为50000。一般线程池大小是远小于50000。所以利用线程池的服务器程序不会为了创建50000而在处理请求时浪费时间,从而提高效率。

代码实现中并没有实现任务接口,而是把Runnable对象加入到线程池管理器(ThreadPool),然后剩下的事情就由线程池管理器(ThreadPool)来完成了

packagemine.util.thread;

importjava.util.LinkedList;
importjava.util.List;

/**
*线程池类,线程管理器:创建线程,执行任务,销毁线程,获取线程基本信息
*/
publicfinalclassThreadPool{
//线程池中默认线程的个数为5
privatestaticintworker_num=5;
//工作线程
privateWorkThread[]workThrads;
//未处理的任务
_task=0;
//任务队列,作为一个缓冲,List线程不安全
privateList<Runnable>taskQueue=newLinkedList<Runnable>();
;

//创建具有默认线程个数的线程池
privateThreadPool(){
this(5);
}

//创建线程池,worker_num为线程池中工作线程的个数
privateThreadPool(intworker_num){
ThreadPool.worker_num=worker_num;
workThrads=newWorkThread[worker_num];
for(inti=0;i<worker_num;i++){
workThrads[i]=newWorkThread();
workThrads[i].start();//开启线程池中的线程
}
}

//单态模式,获得一个默认线程个数的线程池
(){
returngetThreadPool(ThreadPool.worker_num);
}

//单态模式,获得一个指定线程个数的线程池,worker_num(>0)为线程池中工作线程的个数
//worker_num<=0创建默认的工作线程个数
(intworker_num1){
if(worker_num1<=0)
worker_num1=ThreadPool.worker_num;
if(threadPool==null)
threadPool=newThreadPool(worker_num1);
returnthreadPool;
}

//执行任务,其实只是把任务加入任务队列,什么时候执行有线程池管理器觉定
publicvoidexecute(Runnabletask){
synchronized(taskQueue){
taskQueue.add(task);
taskQueue.notify();
}
}

//批量执行任务,其实只是把任务加入任务队列,什么时候执行有线程池管理器觉定
publicvoidexecute(Runnable[]task){
synchronized(taskQueue){
for(Runnablet:task)
taskQueue.add(t);
taskQueue.notify();
}
}

//批量执行任务,其实只是把任务加入任务队列,什么时候执行有线程池管理器觉定
publicvoidexecute(List<Runnable>task){
synchronized(taskQueue){
for(Runnablet:task)
taskQueue.add(t);
taskQueue.notify();
}
}

//销毁线程池,该方法保证在所有任务都完成的情况下才销毁所有线程,否则等待任务完成才销毁
publicvoiddestroy(){
while(!taskQueue.isEmpty()){//如果还有任务没执行完成,就先睡会吧
try{
Thread.sleep(10);
}catch(InterruptedExceptione){
e.printStackTrace();
}
}
//工作线程停止工作,且置为null
for(inti=0;i<worker_num;i++){
workThrads[i].stopWorker();
workThrads[i]=null;
}
threadPool=null;
taskQueue.clear();//清空任务队列
}

//返回工作线程的个数
publicintgetWorkThreadNumber(){
returnworker_num;
}

//返回已完成任务的个数,这里的已完成是只出了任务队列的任务个数,可能该任务并没有实际执行完成
(){
returnfinished_task;
}

//返回任务队列的长度,即还没处理的任务个数
publicintgetWaitTasknumber(){
returntaskQueue.size();
}

//覆盖toString方法,返回线程池信息:工作线程个数和已完成任务个数
@Override
publicStringtoString(){
return"WorkThreadnumber:"+worker_num+"finishedtasknumber:"
+finished_task+"waittasknumber:"+getWaitTasknumber();
}

/**
*内部类,工作线程
*/
{
//该工作线程是否有效,用于结束该工作线程
privatebooleanisRunning=true;

/*
*关键所在啊,如果任务队列不空,则取出任务执行,若任务队列空,则等待
*/
@Override
publicvoidrun(){
Runnabler=null;
while(isRunning){//注意,若线程无效则自然结束run方法,该线程就没用了
synchronized(taskQueue){
while(isRunning&&taskQueue.isEmpty()){//队列为空
try{
taskQueue.wait(20);
}catch(InterruptedExceptione){
e.printStackTrace();
}
}
if(!taskQueue.isEmpty())
r=taskQueue.remove(0);//取出任务
}
if(r!=null){
r.run();//执行任务
}
finished_task++;
r=null;
}
}

//停止工作,让该线程自然执行完run方法,自然结束
publicvoidstopWorker(){
isRunning=false;
}
}
}

④ 在JAVA中如何实现长时间任务

一、问题背景 在应用程序中我们经常需要一个类去完成像数据处理、监听事件或检查另一个类的活动等任务。为了达到这个目标,我们可能使用带有一套锁和消息通知的线程。JAVA 线程API已经很好的文档化,但为了使线程能够正确而高效地运行,程序员仍然需要丰富的编程经验并编写大量的代码。通过应用本篇文章中讨论的框架,程序员能够避免忍受煎熬写大量的代码,快速创建健壮的应用程序。 二、长时间运行任务的程序框架 Framework for long-running tasksThe primary thing about a long-lived task is that it should somehow be kept running ring the application lifetime. The right way to accomplish this is to provide a thread of execution for a particular task. You create a task as a thread or as an implementation of the java.lang.Runnable interface. If you implement Runnable, you can gain better object-oriented design and avoid the single-inheritance problems. You can also more efficiently manipulate with Runnable instances, for example, using a thread pool that usually needs a Runnable instance, not a thread, to run. 关于长时间运行的任务的主要事情是如何在应用程序的生命期使它一直保持运行。实现的恰当方法是提供一个线程来执行这个特定的任务。我们可以通过继承Thread类或实现java.lang.Runnable接口来达到该目标。如果采用实现Runnable接口的方式,就可以能够获得更好的面向对象的设计,同时可以避免JAVA中的单继承问题。另外,我们也能更有效的处理Runnable实例(例如使用线程池通常需要一个Runnable实例而不是线程来运行)。 The essence of the framework is the abstract class Worker ( Listing A), which implements the Runnable interface and provides the helper methods for efficient task handling. Some of the methods are fully implemented, like the run() method, but some are abstract and have to be filled by you. If you want to create a long-running class, you need only to extend the Worker class and implement several abstract methods. Let’s look at these methods in more detail. 框架的基础是一个叫Worker的抽象类,它实现了Runnable接口,并提供了有效处理任务的好方法。这些方法有些已经被实现,如run()方法,但有些是抽象方法,开发人员必须自己来实现。如果要创建一个长时间运行的类,你只需要继承Worker类并实现几个抽象方法。让我们看看这些方法的细节。 The run() method of the Worker class is designed to continuously execute the work() method until it is stopped. The work() method can be responsible for data processing, reaction to some event, file reading or writing, SQL execution, etc. It can throw an exception, so it is a good practice to propagate it and let the run() method handle it. Worker 类的run()方法被设计成只要不停止运行就持续的执行work()方法。work()方法可以负责数据处理、事件响应、文件读写、,执行SQL命令等操作。这样work()方法能够抛出异常,并将异常传给run(),然后由run()方法来处理这些异常。 The run() method has two levels of try-catch clause: outside and inside the while-loop. The first try-catch clause is meant to catch all nonprogrammed exceptions and guarantee that the run() method never exits. The second clause will catch any kind of exceptions belonging to business logic and behave accordingly. If some waiting operation takes place in the work() method (e.g., waiting on an InputStream or a Socket), it is advisable to propagate an InterruptedException. The thing to keep in mind is that the work() method does not need to have any while-loop to keep it going as long as an application runs. The Worker does this for you. run()方法有内外两层try-catch语句:一层处于while-loop循环外,一层在while-loop循环内。前一个try-catch用于捕获非编程异常以确保run()方法不退出。后一个try-catch语句捕获关于业务逻辑和相应行为的各种异常。如果在work()方法中发生了一些等待操作(例如等待一个输入流或一个Socket),抛出一个InterruptedException的方法是可取的。要记住的是只要应用程序在运行,work()方法不需要任何while-loop循环去维持它运行,这一切由Worker代办了。 When the run() method starts, it calls the prepareWorker() which is designed to prepare all resources needed for a long-running task (Listing A). In this method call, you can, for example, establish a database connection or open a file that will be used further. It is especially good to place here some blocking operations like opening a socket, because they will be done in a separate thread and thus will not block the main thread of execution. run()开始时,调用prepareWorker()方法来准备长时间运行任务需要的所有资源(参考程序清单A)。例如 ,在这个方法中可以打开一个将要用到的数据库连接或文件。尤其对于那些像建立一个socket这样的阻塞操作放在这儿是很好的。因为若让它们在一个独立的线程中运行,则不会阻塞主线程的执行。 The opposite of the previous method is the releaseWorker() which is called when the run() method is about to exit (Listing A). Here, you can put the code to dispose of system resources used by this task or to perform other cleanup. This method is similar to java.lang.Object.finalize(), but it is explicitly called before a thread terminates. 与前面方法相反的是releaseWorker(),它在run()方法准备退出时被调用(参考程序清单A)。在该方法中你可以编写那些释放系统资源或执行其它清除动作的代码。该方法类似于java.lang.Object.finalize(),但它在线程中止时被显式的调用。 三、框架中的错误处理机制 Handling errors in the frameworkAnother important method is the handleError(), which takes a java.lang.Throwable as a parameter. This method is called each time an error situation occurs within the run() method. It is up to you how to implement error handling. One way is to log errors and control task termination by calling halt() method (Listing A). The isCondition() method is used to tell whether execution of the work() method can be started, thus allowing granular control over a task. It is useful in event-triggered frameworks when execution of the work() method is pending until some condition?for example, a buffer is not empty?is fulfilled. In Worker’s implementation, the condition is checked upon a lock notification and periodically with a time interval you specify in the setTimeout() method (Listing A). If you don’t need any waiting blocks in a task, just make the isCondition() method always return true. isCondition()方法用于判断work()方法是否能够被执行。因此允许细粒度地控制任务。这在事件触发的框架中非常有用。当work()方法的执行条件未满足时,work方法将被挂起,直到条件完全满足(例如,缓存区非空)。在Worker的实现中这个条件将按在方法setTimeout()中指定的时间周期地检查一个锁通知。如果在任务中不需要任何等待阻塞,仅仅只要使isCondition()方法总是返回真值。四、任务终止时机

⑤ 在java中timertask是什么类

TimerTask是一个实现了Runnable接口的抽象类,代表一个可以被Timer执行的任务。
Timer类是一种线程设施,可以用来实现某一个时间或某一段时间后安排某一个任务执行一次或定期重复执行。该功能和TimerTask配合使用。TimerTask类用于实现由Timer安排的一次或重复执行的某个任务。每一个Timer对象对应的是一个线程,因此计时器所执行的任务应该迅速完成,否则会延迟后续的任务执行。
void cancel()
// 终止此计时器,丢弃所有当前已安排的任务。
int purge()
//从此计时器的任务队列中移除所有已取消的任务。
void schele(TimerTask task, Date time)
//安排在指定的时间执行指定的任务。
void schele(TimerTask task, Date firstTime, long period)
//安排指定的任务在指定的时间开始进行重复的固定延迟执行。
void schele(TimerTask task, long delay)
//安排在指定延迟后执行指定的任务。
void schele(TimerTask task, long delay, long period)
//安排指定的任务从指定的延迟后开始进行重复的固定延迟执行。
void scheleAtFixedRate(TimerTask task, Date firstTime, long period)
//安排指定的任务在指定的时间开始进行重复的固定速率执行。
void scheleAtFixedRate(TimerTask task, long delay, long period)
//安排指定的任务在指定的延迟后开始进行重复的固定速率执行。
+++++++++++++++++++++++++++++++++++++++++++++++++++
boolean cancel()
//取消此计时器任务。
abstract void run()
//此计时器任务要执行的操作。
long scheledExecutionTime()
//返回此任务最近实际 执行的已安排 执行时间。
++++++++++++++++++++++++++++++++++++++++++++++++++++++
package zzs.time.demo;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimerTask;

public class MyTask extends TimerTask {

@Override
public void run() {
// TODO Auto-generated method stub
SimpleDateFormat simpleDateFormat=null;
simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
System.out.println("当前的系统时间为:"+simpleDateFormat.format(new Date()));

}

}

+++++++++++++++++++++++++++++++++++++++++++++++++++++++
package zzs.time.demo;

import java.util.Timer;

public class TestTask {

/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
Timer timer=new Timer();
MyTask myTask=new MyTask();
timer.schele(myTask, 1000, 2000);
// Thread.sleep(5000);
//timer.cancel();

}
}
运行结果:
当前的系统时间为:2011-07-10 15:37:44:831
当前的系统时间为:2011-07-10 15:37:46:786
当前的系统时间为:2011-07-10 15:37:48:786
当前的系统时间为:2011-07-10 15:37:50:786
当前的系统时间为:2011-07-10 15:37:52:786
当前的系统时间为:2011-07-10 15:37:54:786

⑥ java 线程 设置每周的某一天的某个时间执行一次,用哪个方法。SchelerTask

有多种思路可以实现。
最直接最简单就是用:java.util.Timer 类的
scheleAtFixedRate(TimerTask task, Date firstTime, long period) 方法。
第一个参数执行的任务,这个你应该知道了。第二个参数开始运行的时间,也就是第一次运行的时间。第三个参数是运行周期,以毫秒为单位。你可以算出一周时间的毫秒数为:

1000*60*60*24*7 = 604800000 毫秒。把这个作为第三个参数就行了。
也可以使用:schele(TimerTask task, Date time) 方法
每次运行之后,用 new Date(time.getTime()+604800000) 的方法创建出下一周同一个时间,然后再次调用这个方法,用新日期作为参数。用这第二种方法可以实现你关掉程序,重新开之后,仍然会在指定时间运行,当然你要把这个日期保存下来,重开的时候加载。

⑦ java事件触发计时器后二十四小时后只执行一次业务逻辑

java中有个定时任务 java.util.TimerTask

用法很简单

classMyTaskextendsjava.util.TimerTask{
@Override
publicvoidrun(){
//这个任何所执行的版代码
}
}


java.util.Timertimer=newTimer(true); //treu就是守护线程
MyTasktask=newMyTask();
//开始执行任务权,第一个参数是任务,第二个是延迟时间,第三个是每隔多长时间执行一次
timer.schele(task,0,1000*60*60*24);
阅读全文

与javatask相关的资料

热点内容
秘密文件一般保存多少年 浏览:952
文件夹隐藏后怎么恢复 浏览:251
文件恢复360 浏览:914
c打开文件夹选择文件 浏览:430
工程变更文件需要多少份 浏览:227
风云三国28文件修改器 浏览:461
哪个app有pets词汇 浏览:926
苹果6s看电影屏幕变暗 浏览:474
怎么注册文件 浏览:600
excel数字怎么自动填入相同数据 浏览:652
上百万条数据用什么软件处理 浏览:680
打开的程序不是全屏 浏览:837
不用u盘传文件 浏览:673
什么少儿编程课网课哪个好 浏览:98
win101706开始界面 浏览:152
java二维数据初始化 浏览:174
listmapjava 浏览:296
利用视频赚钱的网站有哪些 浏览:766
iphone4sios711降级 浏览:246
探岳数据线口在哪里 浏览:654

友情链接