① 用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);