当程序启动时,在后台自动调用一个方法,而不使用线程。
class Abc
{
main()
{
do something......
}
}
class xyz
{
public void show()
{
call every 1 minute in background
do something.....
with out affect main method
}
}
答案 0 :(得分:0)
只有1个帖子,你不能同时做两件事。你必须创建另一个线程。
答案 1 :(得分:0)
假设您需要每隔1分钟从main调用show()而不会干扰main()代码
class Abc
{
main()
{
Thread mythread = new Thread()
{
xyz myClass = new xyz();
public void run()
{
while(true)
{
myClass.show() // this will execute
thread.sleep(60000); // this will pause for a bit but wont affect your main code, add this in between try and catch to pause this thread alone withotu affecting main one for 1 min and it goes again and calls show()
}
}
}
do something......
}
}
class xyz
{
public void show()
{
// whatever you type here will now run every 1 min, without affecting your main code
}
}
答案 2 :(得分:0)
您可以使用ScheduledExecutorService来完成此任务。
public static class Scheduler {
private Runnable task;
private ScheduledExecutorService executorService;
public Scheduler(Runnable task, ScheduledExecutorService executorService) {
this.task = task;
this.executorService = executorService;
}
public void start(long startDelay, long period ) {
executorService.scheduleAtFixedRate(task, startDelay, period, TimeUnit.MINUTES);
}
}