欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

用synchronized实现互斥锁

程序员文章站 2022-06-11 16:21:06
package seday10;/** * @author xingsir * 互斥锁 * 当使用synchronized锁定多个代码片段,并且他们指定的同步监视器对象是同一个时,那么这些代码片段之间就是互斥的, * 多个线程不能同时在这些代码片段中运行。 */public class syncDe ......

package seday10;
/**
* @author xingsir
* 互斥锁
* 当使用synchronized锁定多个代码片段,并且他们指定的同步监视器对象是同一个时,那么这些代码片段之间就是互斥的,
* 多个线程不能同时在这些代码片段中运行。
*/
public class syncdemo4 {

public static void main(string[] args) {
boo boo = new boo();//实例化
thread t1 = new thread() {//线程一
public void run() {
boo.ma();//调用方法
}
};
thread t2 = new thread() {//线程二
public void run() {
boo.mb();//调用方法
}
};
t1.start();//启动
t2.start();//启动

}

}
class boo{
public synchronized void ma() {//synchronized锁定多个代码片段
try {
thread thread =thread.currentthread();//主线程
system.out.println(thread.getname()+":ma方法正在执行...");//打印
thread.sleep(5000);//休眠5000毫秒
system.out.println(thread.getname()+":ma方法执行完毕");//打印
} catch (exception e) {
// todo: handle exception
}

}

public void mb() {
synchronized(this) {//synchronized锁定多个代码片段
try {
thread thread=thread.currentthread();//主线程
system.out.println(thread.getname()+":正在执行mb方法...");//打印
thread.sleep(5000);//休眠5000毫秒
system.out.println(thread.getname()+":执行mb方法完毕!");//打印
} catch (exception e) {
e.printstacktrace();

}
}
}

}