0

我想要做的是,传递clientIdClearSession()并使用clientIdinrun()来调用session.loadByLastAccessed()。但它抛出的错误是......

Service.java:117: non-static variable this cannot be referenced from a static context 
    at Thread t = new Thread(new ClearSession(clientId)) (since it is inner class)

如果我将类更改为is static,它将在session.loadByLastAccessed(entityManager, clientId);since entityManageris上引发错误non-static

关于如何start()从方法中创建线程static并传递non-static变量的任何想法?

这是我的代码...

private EntityManager entityManager; //declared within class along with code below.


public static void initClients()
        throws SessionServiceException
    {
        Properties properties = ApplicationConfig.getInstance().getProperties();
        Set<Object> keys = properties.keySet();
        String clientId = null;
        for (Object keyObject : keys)
        {
            String key = (String)keyObject;
            if (key.startsWith(SessionFactory.CLIENT_PREFIX))
            {
                clientId = StringUtils.substringAfter(key, SessionFactory.CLIENT_PREFIX);
                SessionFactory.getSessionIntf(clientId);
            }
        }

        if(!StringUtils.equals("branch", clientId ))
        {
            Thread t = new Thread(new ClearSession(clientId));
            t.start();
        }
    }

private class ClearSession implements Runnable 
{
    private String clientId = "";

    public ClearSession(String clientId) 
    {
        this.clientId = clientId;
    }

    public void run() 
    {
        try 
        {
            // Pause for 2 hours
            Thread.sleep(7200000);
            // get client session
            AbstractImpl session = SessionFactory.getSessionIntf(clientId);
            session.loadByLastAccessed(entityManager, clientId);

        } catch (InterruptedException ie) {
            throw ie;
        }
    }
}
4

1 回答 1

0

我现在明白了。你有private class,这意味着它是内部类。默认情况下,内部类隐式引用外部类的this. 只需将类声明为private static class或将其移出即可。

于 2012-06-15T19:34:58.457 回答