java解惑(谜题76。)
java解惑(谜题76。。)谜题76:乒乓public class PingPong {public static void main(String[] args) {Thread
java解惑(谜题76。。)
谜题76:乒乓
public class PingPong {public static void main(String[] args) {Thread t = new Thread(){public void run(){pong();}};t.run();System.out.println("Ping");}static synchronized void pong(){System.out.println("Pong");}}在多线程程序中,通常正确的观点是程序每次运行的结果都有可能发生变化,但是上面这段程序总是打印出相同的内容。在一个同步化的静态方法执行之前,它会获取与它的class对象相关的一个管程(monitor)锁。在上面程序中,主线程会在创建第二个线程之前获得与PingPong.class相关联的那个锁。只有主线程占着这个锁,第二个线程就不可能执行同步化的静态方法。具体讲,在main方法打印了Ping并且执行结束后,第二个线程才能执行pong方法。只有当主线程放弃那个锁的时候,第二个线程才能允许获得这个锁并且打印pong。根据分析,结果应该打印出PingPong,但结果是PongPing。为甚?
这段程序并不是一个多线程程序。它确实是创建了第二个线程,但是它从未启动这个线程。相反地,主线程会调用那个新的线程实例的run方法,这个方法与主线程同步地运行。
只需将t.run();改为t.start()来启动线程。
public class Main95 {public static void main(String[] args) {int count = 0;for(int i =0;i<100;i++);{count++;}System.out.println(count);}}打印1,因为;的缘故
下面是一个反射的例子会打印出什么呢?
import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.util.HashSet;import java.util.Set;import java.util.Iterator;public class Ref {public static void main(String[] args) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {Set<String> s = new HashSet<String>();s.add("foo");Iterator it = s.iterator();Method m = it.getClass().getMethod("hasNext");System.out.println(m.invoke(it));}}Exception in thread "main" java.lang.IllegalAccessException: Class chapter9.Ref can not access a member of class java.util.HashMap$HashIterator with modifiers "public final"
at sun.reflect.Reflection.ensureMemberAccess(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)hasNext方法是公共的。
这个类型是由从it.getClass()方法返回的Class对象表示的。这时迭代器的动态类型,它恰好是私有的嵌套类java.util.HashMap.KeyIterator。出现这种异常,就是因为该类不是公共的。访问位于其他包中的非公共类型的成员是不合法的。