62,616
社区成员
发帖
与我相关
我的任务
分享
public void startTest()
timeMng=new java.util.Timer();
timeCvt=new java.util.TimerTask()
{
public void run()
{
try
{
if(rtveLen >=(9))
{
System.out.println("222222222222222222222"+"-"+rtveLen);
rtveLen=0;
if(taskCount>0)
{
synchronized(JCLOCKTT)
{
getJcDevice();//去得到上些东西的方法
}
}
}
else
{
rtveLen++;
}
}
catch(Exception e)
{
FunOfSelf.println("监测线程处理过程出错"+e);
}
};
};
getJcDevice();//去得到上些东西的方法
timeMng.schedule(timeCvt,3,1000);//启动定时器
}
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
/**
* 具有线程池的工作队列。 传进来的任务先放入任务队列中。 然后唤醒正在等待任务的任一线程来执行此任务并把此任务从任务队列中删除。
* 如果任务队列中没有要执行的任务,则线程调用wait()等待任务到来。
*
* @author Biao
*
*/
public class WorkQueue {
private Thread[] threads;
private List<Runnable> taskQueue;
public WorkQueue(int threadCount) {
taskQueue = new LinkedList<Runnable>();
threads = new Thread[threadCount];
for (int i = 0; i < threadCount; ++i) {
threads[i] = new PoolWorker();
threads[i].start();
}
}
public void execute(Runnable r) {
synchronized (taskQueue) {
taskQueue.add(r);
taskQueue.notify();
}
}
private class PoolWorker extends Thread {
public void run() {
Runnable r = null;
while (true) {
// [线程要想调用一个对象的wait()方法就要先获得该对象的监视锁,而一旦调用wait()后又立即释放该锁]
synchronized (taskQueue) {
while (taskQueue.isEmpty()) {
try {
System.out.println("Wait");
taskQueue.wait();
} catch (InterruptedException e) {
}
}
r = taskQueue.remove(0);
}
try {
r.run();
} catch (RuntimeException e) {
}
}
}
}
public static void main(String[] args) {
WorkQueue wq = new WorkQueue(4);
final Random ran = new Random(System.currentTimeMillis());
class MyRunnable implements Runnable {
private int id;
public MyRunnable(int id) {
this.id = id;
}
public void run() {
try {
for (int i = 0; i < 10; ++i) {
int interval = ran.nextInt(2000);
Thread.sleep(interval);
System.out.println("Id:" + id + "--Time:" + i + ":" + interval);
}
} catch (Exception e) {
}
}
}
for (int i = 0; i < 3; ++i) {
wq.execute(new MyRunnable(i));
}
}
}
Java定时任务的实现
①继承TimerTask,重写run方法
package bamboo.task;
import java.util.TimerTask;
public class TimeTaskTest extends TimerTask{
@Override
public void run() {
System.out.println("hi");
}
}
②通过timer来设置某个时间来调用,或者是相隔多长时间调用
package bamboo.test;
import java.util.Date;
import java.util.Timer;
import bamboo.task.TimeTaskTest;
public class TimeTest {
static TimeTaskTest test=new TimeTaskTest();
public static void main(String [] args){
Timer timer=new Timer();
//启动和间隔的时间 1000毫秒
//timer.schedule(test,0,1000);
//设置什么时候执行
//timer.schedule(test, new Date());
}
}