synchronized详解2

/*
面试题
*/
public class fuck10{
public static void main(String[] args) throws InterruptedException{
myclass mc=new myclass();
processor p=new processor(mc);

Thread t1=new Thread(p);
t1.setName("t1");
Thread t2=new Thread(p);
t2.setName("t2");

t1.start();

//延迟,保证t1线程先执行
Thread.sleep(1000);
t2.start();
}
}


class processor implements Runnable{
myclass mc;

processor(myclass mc){
this.mc=mc;
}

public void run(){
if(Thread.currentThread().getName().equals("t1") ){
mc.m1();
}

if(Thread.currentThread().getName().equals("t2") ){
mc.m2();
}

}
}


class myclass {

public synchronized void m1(){
try{Thread.sleep(10000);}catch(InterruptedException e){}
System.out.println("m1````");
}

public synchronized void m2(){
System.out.println("m2````");
}
}

猜你喜欢

转载自blog.csdn.net/rolic_/article/details/80742731