一道常见面试题的答案
package aa;
public class MutiS {
public static int m=0;
public static void main(String []args){
MutiS s = new MutiS();
Add t1 =s.new Add();
Add t2 =s.new Add();
Dec r = s.new Dec();
Thread t3 = new Thread(r, "第三个线程 ");
Thread t4 = new Thread(r, "第四个线程 ");
t1.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println( "1m-- "+m);
t2.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println( "2m-- "+m);
t3.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println( "3m-- "+m);
t4.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println( "4m-- "+m);
}
class Add extends Thread{
Add(){
}
public synchronized void run(){
m=m+1;
//System.out.print( "mm "+m);
}
}
class Dec implements Runnable{
Dec(){
}
public synchronized void run(){
m=m-1;
//System.out.print( "mmn "+m);
}
}
}
------解决方案--------------------不懂~
------解决方案--------------------不懂
------解决方案--------------------1m--1
2m--2
3m--1
4m--0
这是运行结果! 主要是synchronized的应用.线程休眠期间,并没有放弃对象锁
------解决方案--------------------同意楼上的看法.