synchronized块和synchronized函数锁住的都是当前对象。
class threadOne implements Runnable{
public static int num=0;
public static Object ob=new Object();
public boolean b=true;
@Override
public void run(){
if(b==true){
synchronized (this){
try{
Thread.sleep(600);
}catch (Exception e){
e.printStackTrace();
}
while(num!=10){
num+=1;
System.out.println("run-num:"+num);
}
}
}else{
compute();
}
}
public synchronized void compute(){
while(num!=10){
num+=1;
System.out.println("compute-num:"+num);
}
}
}
public class threadTest {
public static void main(String ...args){
threadOne one=new threadOne();
Thread t1=new Thread(one);
Thread t2=new Thread(one);
t1.start();
try{
Thread.sleep(300);
}catch (Exception e){
e.printStackTrace();
}
one.b=false;
t2.start();
}
}
D:\Java\jdk1.8.0_151\bin\java.exe "-javaagent:D:\idea\IntelliJ IDEA Community Edition 2018.2.5\lib\idea_rt.jar=1426:D:\idea\IntelliJ IDEA Community Edition 2018.2.5\bin" -Dfile.encoding=UTF-8 -classpath D:\Java\jdk1.8.0_151\jre\lib\charsets.jar;D:\Java\jdk1.8.0_151\jre\lib\deploy.jar;D:\Java\jdk1.8.0_151\jre\lib\ext\access-bridge-64.jar;D:\Java\jdk1.8.0_151\jre\lib\ext\cldrdata.jar;D:\Java\jdk1.8.0_151\jre\lib\ext\dnsns.jar;D:\Java\jdk1.8.0_151\jre\lib\ext\jaccess.jar;D:\Java\jdk1.8.0_151\jre\lib\ext\jfxrt.jar;D:\Java\jdk1.8.0_151\jre\lib\ext\localedata.jar;D:\Java\jdk1.8.0_151\jre\lib\ext\nashorn.jar;D:\Java\jdk1.8.0_151\jre\lib\ext\sunec.jar;D:\Java\jdk1.8.0_151\jre\lib\ext\sunjce_provider.jar;D:\Java\jdk1.8.0_151\jre\lib\ext\sunmscapi.jar;D:\Java\jdk1.8.0_151\jre\lib\ext\sunpkcs11.jar;D:\Java\jdk1.8.0_151\jre\lib\ext\zipfs.jar;D:\Java\jdk1.8.0_151\jre\lib\javaws.jar;D:\Java\jdk1.8.0_151\jre\lib\jce.jar;D:\Java\jdk1.8.0_151\jre\lib\jfr.jar;D:\Java\jdk1.8.0_151\jre\lib\jfxswt.jar;D:\Java\jdk1.8.0_151\jre\lib\jsse.jar;D:\Java\jdk1.8.0_151\jre\lib\management-agent.jar;D:\Java\jdk1.8.0_151\jre\lib\plugin.jar;D:\Java\jdk1.8.0_151\jre\lib\resources.jar;D:\Java\jdk1.8.0_151\jre\lib\rt.jar;E:\threadTest\out\production\threadTest threadTest
run-num:1
run-num:2
run-num:3
run-num:4
run-num:5
run-num:6
run-num:7
run-num:8
run-num:9
run-num:10
Process finished with exit code 0
以上是运行结果,证明了后面compute函数无法竞争到锁。
有问题可以在留言区交流。