시간 초과 작업의 실현에 관하여
3723 단어 thread
package test.thread;
import java.util.Timer;
import java.util.TimerTask;
public class MainThread {
private Object lock = new Object();
public void waitLock() throws InterruptedException {
synchronized (lock) {
lock.wait();
}
}
public void notifyLock() {
synchronized (lock) {
lock.notify();
}
}
/**
* @param args
* : , , ,
* : , , , , 。
* @throws InterruptedException
*/
public static void main(String[] args) {
MainThread mainThread = new MainThread();
for (int i = 2; i <= 20; i += 2) {
System.out.println("start task!" + i);
ProccessThread proccessThread = new ProccessThread(mainThread,i * 1000);
MonitorThread monitorThread = new MonitorThread(mainThread);
long maxProccessTime = 8 * 1000;//
Timer timer = new Timer();
timer.schedule(monitorThread, maxProccessTime);
proccessThread.start();
try {
mainThread.waitLock();
} catch (InterruptedException e) {
e.printStackTrace();
}
proccessThread.stop();
timer.cancel();
System.out.println("end task!" + i);
}
}
}
/**
*
* @author liuhui
*
*/
class MonitorThread extends TimerTask {
private MainThread mt;
public MonitorThread(MainThread mt) {
super();
this.mt = mt;
}
@Override
public void run() {
System.out.println("ThreadID:" + " MonitorThread running!");
mt.notifyLock();
}
}
/**
*
* @author liuhui
*
*/
class ProccessThread implements Runnable {
private MainThread mt;
private Thread thread;
private long processTime;
public static int sec = 1;
public ProccessThread(MainThread mt, long processTime) {
super();
this.mt = mt;
this.processTime = processTime;
}
private void doSomething() {
try {
// do something
// thread.sleep(100*1000); //
// thread.sleep(1*1000); //
thread.sleep(processTime); //
System.out.println("ThreadID:" + thread.getId() + ">>> Normal Process! processTime=" + processTime);
} catch (InterruptedException e) {
// e.printStackTrace();
System.out.println("ThreadID:" + thread.getId() + ">>> AbNormal Proccess! processTime=" + processTime);
}
}
public void run() {
System.out.println("ThreadID:" + thread.getId() + ">>> starting!");
doSomething();
mt.notifyLock();
System.out.println("ThreadID:" + thread.getId() + ">>> ending ok!");
}
public void start() {
thread = new Thread(this);
thread.start();
}
public void stop() {
thread.interrupt();// , interrupt, (run )
thread.stop();
try {
Thread.sleep(sec * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("ThreadID:" + thread.getId() + ">>> stoping end!");
thread = null;
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Exception in thread main java.lang. NoClassDefFoundError 오류 해결 방법즉,/home/hadoop/jarfile) 시스템은 Hello World 패키지 아래의class라는 클래스 파일을 실행하고 있다고 오인하여 시스템의 CLASSPATH 아래 (일반적으로 현재 디렉터리를 포함) Hell...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.