java在线程和内部类中的使用final关键字
1.线程内只能访问线程外的final变量
2.局部内部类
内部类访问了方法中的final剋行的变量name
public class LocalInnerClass { private static Test monitor = new Test(); private int count = 0; Counter getCounter(final String name) { // A local inner class: class LocalCounter implements Counter { public LocalCounter() { // Local inner class can have a constructor System.out.println("LocalCounter()"); } public int next() { System.out.print(name); // Access local final return count++; } } return new LocalCounter(); } }
3.匿名内部类参数必须为final类型
匿名内部内访问了外面的final int dynaimcUserId ,final int dynamicId,final String commentDataUrl
private void sendRequestWithHttpURLConnectionHaveParam(final int dynaimcUserId ,final int dynamicId,final String commentDataUrl) { Thread t = new Thread(new Runnable() { @Override public void run() { try { OkHttpClient client = new OkHttpClient(); RequestBody requestBody = new FormBody.Builder().add("userId",dynaimcUserId+"").add("dynamicId",dynamicId+"").build();// Request request = new Request.Builder().url(commentDataUrl).post(requestBody).build(); Response response = client.newCall(request).execute(); String responseData = response.body().string(); Log.d(TAG, "run: "+responseData); // parseJSONWithJSONObject(responseData); // responseData=new String(responseData.getBytes("iso8859-1"),"utf-8"); Message message=Message.obtain(handler,1,2,3,responseData); message.sendToTarget(); testJson=responseData; Log.d(TAG, "run:testJson "+testJson); // initView(); } catch (IOException e) { e.printStackTrace(); } } }); t.start(); try { t.join(); } catch (InterruptedException e) { e.printStackTrace(); } }