这是我的Timer
调度程序
timer.schedule(new SuperOne(),new Date(),10);
在run
方法中的SuperOne
类中,我正在调用synchronized
方法通过使用上面的代码该任务仅工作一次。
我的要求是它必须每分钟(60秒)调用synchronized
方法。
这里计时器调度程序没有按我的预期工作...是因为我正在运行 synchronized
方法吗?
请帮助我
*编辑:它第一次工作(调用一次)并且在 10 毫秒后不调用 *
这是必须运行的代码
private boolean proxyEnabled=false;
public synchronized void statusChecker()
{
StopWatch sWatch = new StopWatch();
ResourceBundle resource = ResourceBundle.getBundle("resources.application");
System.out.println(resource.getString("url"));
try {
URL url = new URL("https://www.google.com/");
HttpURLConnection urlConnection;
if(proxyEnabled) {
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxYhost", portNumber));
sWatch.start();
urlConnection =(HttpURLConnection) url.openConnection(proxy);
System.out.println(urlConnection);
} else {
urlConnection =(HttpURLConnection)url.openConnection();
sWatch.start();
}
System.out.println(urlConnection.getResponseCode());
in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
if(in!=null)
{
System.out.println("The resopose TIme is -- >"+ sWatch.toString());
}else
{
System.exit(0);
}
}catch(Exception e)
{
e.printStackTrace();
System.exit(0);
}finally
{
sWatch.stop();
}
}
扩展TimerTask
的类
public class SuperOne extends TimerTask{
boolean flag = false;
@Override
public synchronized void run() {
// TODO Auto-generated method stub
try {
System.out.println("*** * ** Thread started ** ** *** ");
Thread th = Thread.currentThread();
System.out.println(th.isAlive());
CheckServer cs = new CheckServer();
cs.statusChecker();
}
catch(Exception e)
{
System.out.println("Exception in Run IterFace "+e);
e.printStackTrace();
}
}
}
最佳答案
您已经使运行
同步
,这意味着一次只有一个线程可以访问该函数(这意味着实际上只有一个任务可以在同一时间处于 Activity 状态)一次)。我不相信这就是你想要做的。我想您打算做的就是使 run
在执行期间调用的内容同步
,以便一次只有一个正在运行的任务可以调用它以确保一致性。
很多人都被 synchronized
的作用所困扰,因为它没有做很多人期望的事情(尽管如果你考虑一下,它确实做了它的名字所暗示的事情)它的常见用例)。请参阅 Java synchronized tutorial了解更多。
关于java - TIMEr 在 java 中无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22291016/