当前位置: 技术问答>java相关
想用timer实现每隔1秒执行一次abc()函数。不知道该如何写?
来源: 互联网 发布时间:2015-04-26
本文导语: 请给代码 | import java.util.*; public class test{ public static void main(String[] args){ MyTask task = new MyTask(); java.util.Timer timer = new Timer(); timer.schedule(task, 1000, 10000); } } class MyTask e...
请给代码
|
import java.util.*;
public class test{
public static void main(String[] args){
MyTask task = new MyTask();
java.util.Timer timer = new Timer();
timer.schedule(task, 1000, 10000);
}
}
class MyTask extends java.util.TimerTask{
void abc(){
System.out.println("abc()");
}
public void run(){
try{
while(true){
abc();
Thread.sleep(3000);
}
}catch(java.lang.InterruptedException ie){
}
}
}
public class test{
public static void main(String[] args){
MyTask task = new MyTask();
java.util.Timer timer = new Timer();
timer.schedule(task, 1000, 10000);
}
}
class MyTask extends java.util.TimerTask{
void abc(){
System.out.println("abc()");
}
public void run(){
try{
while(true){
abc();
Thread.sleep(3000);
}
}catch(java.lang.InterruptedException ie){
}
}
}
|
public class myThread extends Thread {
public int num;
int threadid;
public myThread(int id) {
num=0;
threadid=id;
}
public void run() {
// compute primes larger than minPrime
for(;;)
{
num++;
try{
sleep(500);
}catch(Exception e)
{
}
System.out.println("mythread go threadid="+Integer.toString(threadid)+" num="+Integer.toString(num));
}
}
}
//thread
public int num;
int threadid;
public myThread(int id) {
num=0;
threadid=id;
}
public void run() {
// compute primes larger than minPrime
for(;;)
{
num++;
try{
sleep(500);
}catch(Exception e)
{
}
System.out.println("mythread go threadid="+Integer.toString(threadid)+" num="+Integer.toString(num));
}
}
}
//thread