Java並發編程示例(五):線程休眠與恢復。本站提示廣大學習愛好者:(Java並發編程示例(五):線程休眠與恢復)文章只能為提供參考,不一定能成為您想要的結果。以下是Java並發編程示例(五):線程休眠與恢復正文
本文實例講述了Java斷定時光段內文件能否更新的辦法。分享給年夜家供年夜家參考。詳細完成辦法以下:
1.准時器
private Timer timer;
/**
* 簡略單純准時器
* @param delay 多久後開端履行。毫秒
* @param period 履行的距離時光。毫秒
*/
public void test(long delay, long period) {
timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
//你 的 操作辦法
System.out.println(System.currentTimeMillis());
}
}, delay, period);
}
2.深化版
package classloader;
/**
* @author vma
*/
// 自界說一個類加載器
public class DynamicClassLoader extends ClassLoader {
public Class<?> findClass(byte[] b) throws ClassNotFoundException {
return defineClass(null, b, 0, b.length);
}
package classloader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
/**
* @author vma
*/
public class ManageClassLoader {
DynamicClassLoader dc =null;
Long lastModified = 0l;
Class c = null;
//加載類, 假如類文件修正過加載,假如沒有修正,前往以後的
public Class loadClass(String name) throws ClassNotFoundException, IOException{
if (isClassModified(name)){
dc = new DynamicClassLoader();
return c = dc.findClass(getBytes(name));
}
return c;
}
//斷定能否被修正過
private boolean isClassModified(String filename) {
boolean returnValue = false;
File file = new File(filename);
if (file.lastModified() > lastModified) {
returnValue = true;
}
return returnValue;
}
// 從當地讀取文件
private byte[] getBytes(String filename) throws IOException {
File file = new File(filename);
long len = file.length();
lastModified = file.lastModified();
byte raw[] = new byte[(int) len];
FileInputStream fin = new FileInputStream(file);
int r = fin.read(raw);
if (r != len) {
throw new IOException("Can't read all, " + r + " != " + len);
}
fin.close();
return raw;
}
}
3.thread辦法
class Thread1 extends Thread{
public void run(){
//挪用營業辦法(檢查文件能否轉變)
Thread.currentThread().sleep("100000");
}
願望本文所述對年夜家的Java法式設計有所贊助。
bsp; @OverrideFileMain類的完全代碼
package com.diguage.books.concurrencycookbook.chapter1.recipe5;
import java.util.concurrent.TimeUnit;
/**
* 演示線程休眠和恢復
* Date: 2013-09-19
* Time: 00:29
*/
public class FileMain {
public static void main(String[] args) {
FileClock clock = new FileClock();
Thread thread = new Thread(clock);
thread.start();
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
thread.interrupt();
}
}