Java多线程中使用synchronized说明

 1.在类中方法上加上
  synchronized关键字,是对整个对象加锁,当一个线程访问带有synchronized的方法时,其他带有synchronized的方法的访问就都会阻塞。
  样例:
public class ThreadTest {
public static void main(String[] args) {
Stu stu = new Stu();
StuThread1 t1 = new StuThread1(stu);
t1.start();
StuThread2 t2 = new StuThread2(stu);
t2.start();
}
}
class StuThread1 extends Thread {
Stu stu;
public StuThread1(Stu stu) {
this.stu = stu;
}
public void run() {
stu.read1();
}
}
class StuThread2 extends Thread {
Stu stu;
public StuThread2(Stu stu) {
this.stu = stu;
}
public void run() {
stu.read2();
}
}
class Stu {
public synchronized void read1() {
System.out.println("read1 begin");
try {
Thread.currentThread().sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("read1 end");
}
public synchronized void read2() {
System.out.println("read2 begin");
try {
Thread.currentThread().sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("read2 end");
}
}
打印结果为(两个线程是顺序执行的):
read1 begin
read1 end
read2 begin
read2 end
  如果去掉read2前面的synchronized关键字,打印为(线程出现了交叉执行):
read1 begin
read2 begin
read2 end
read1 end
  修改read2方法,
public void read2() {
synchronized(this)
{
System.out.println("read2 begin");
try {
Thread.currentThread().sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("read2 end");
}
}
  对this进行加锁,结果同一次,线程是顺序执行的。


最新内容请见作者的GitHub页:http://qaseven.github.io/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值