一道多线程的笔试题,看晕掉了,求大牛指点!!
public class Main {
Integer i=1;
public Main(){}
public static void main(String[] args)throws Exception {
// TODO Auto-generated method stub
final Main t =new Main();
synchronized(t.i){
Thread thread =new Thread(){
public void run(){
for(;;){
synchronized(t.i){
System.out.println("a:"+(++t.i));
try{
Thread.sleep(100);
}catch(InterruptedException ex){
ex.printStackTrace();
}
t.i.notifyAll();
}
}
}
};
thread.start();
t.i.wait();
System.out.println("b:"+(++t.i)); }
}
}
求此程序的输出
A 输出a:2,程序抛出异常;
B 输出a:2,程序进入等待;
一直不理解的是sleep之后用notifyAll会出现什么情况呢 --------------------编程问答-------------------- public void run(){
for(;;){
synchronized(t.i){
//换个位置看看。
t.i.notifyAll();
System.out.println("a:"+(++t.i));
try{
Thread.sleep(100);
}catch(InterruptedException ex){
ex.printStackTrace();
}
}
}
} --------------------编程问答-------------------- 坑是在System.out.println("a:"+(++t.i));
如果没有这个是正确的,因为共享对象是同一个。
如果加了上面的++运算,i的引用就变为了新的对象,这时候同步块就出错了 --------------------编程问答-------------------- 感觉楼上说的很对的,应该是两个线程共享对象的引用发生变化引起的。
补充:Java , Java相关