java synchronized 功能 清晰 解释

关键字synchronized 的理解

1.锁定当前对象;

2.保证当前对象中 [b]所有[/b] 有 synchronized 标志的方法 同一时间 只能有一个线程访问

3.对当前对象中,没有synchronized标志的方法,没有限制

-----------------------------------------------------------------

public class LockTest {
public synchronized void say(){
Thread t = Thread.currentThread();
System.out.println("say is call by " + t);
}
public synchronized void say1(){

Thread t = Thread.currentThread();
System.out.println("say1 is call by " + t);
try {
t.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// System.out.println("say1 is call by " + t);
System.out.println("say1 " + t + "执行完毕");
}
public synchronized void say2(){
Thread t = Thread.currentThread();
try {
t.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("say2 is call by " + t);
System.out.println("say2 " + t + "执行完毕");
}
}



public class Test {
private static LockTest lockTest = new LockTest();
private static Thread test1;
private static Thread test2;
public static void main(String[] args) {

Test test = new Test();
test.ini();

test1.start();
test2.start();
lockTest.say();
// lockTest.say1();
// lockTest.say2();
}
private void ini(){
test1 = new Thread(new RunTest1());
test2 = new Thread(new RunTest2());

}
private class RunTest1 implements Runnable{

@Override
public void run() {
System.out.println("线程0开始启动");
lockTest.say1();
}

}
private class RunTest2 implements Runnable{

@Override
public void run() {
System.out.println("线程1开始启动");
lockTest.say2();
}

}
}



-------------------------------------------------------------
运行结果:
say is call by Thread[main,5,main]
线程1开始启动
线程0开始启动
say2 is call by Thread[Thread-1,5,main]
say2 Thread[Thread-1,5,main]执行完毕
say1 is call by Thread[Thread-0,5,main]
say1 Thread[Thread-0,5,main]执行完毕

因cpu分配给线程 时间片,不是每次运行结果都一样(mian,thread0,thread1的顺序)
单不会出现say1, say2 或 线程0,线程1 嵌套执行的情况
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值