多个线程多把锁

来源:互联网 发布:电信4g网络覆盖范围 编辑:程序博客网 时间:2024/05/22 09:48
public class MulityThread{
private static int num = 0;

public static  synchronized void printNum(String tag){//如果加static关键字,那么这个方法就是公使用的,不管实例多少对象,它都只有一把锁
try{
if(tag.equals("a")){
num = 100;
System.out.println("tag a,set num over!");
Thread.sleep(1000);
}else{
num = 200;
System.out.println("tag b,set num over!");
}
System.out.println("tag "+tag+",num = "+num);
}catch(InterruptedException e){
e.printStackTrace();
}
}
 
public static void main(String[] args) {
final MulityThread m1 = new MulityThread();
final MulityThread m2 = new MulityThread();

Thread t1 = new Thread(new Runnable() {

@Override
public void run() {
m1.printNum("a");
}
});

Thread t2 = new Thread(new Runnable() {

@Override
public void run() {
m2.printNum("b");
}
});

t1.start();
t2.start();
}
原创粉丝点击