synchronized锁失效

xiaoning_131 xiaoning_131 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
代码如下:
package com.wn.thread;
public class SynchronizedTest extends Thread {
public synchronized void f(String name, int i){
System.out.println(name+"调用了f"+i+"次");
}

public synchronized void g(String name, int i){
System.out.println(name+"调用了g"+i+"次");
}

public static void main(String[] agrs){
SynchronizedTest st=new SynchronizedTest();
test t=new test(st);
test1 t1=new test1(st);
t.start();
t1.start();
}
}
class test extends Thread{
SynchronizedTest st;
test(SynchronizedTest st){
this.st=st;
}
@Override
public void run() {
this.setName("线程1");
for(int i=0;i<1000;i++){
st.f(this.getName(), i+1);
}
}
}
class test1 extends Thread{
SynchronizedTest st;
test1(SynchronizedTest st){
this.st=st;
}
@Override
public void run() {
this.setName("线程2");
for(int i=0;i<1000;i++){
st.g(this.getName(), i+1);
}
}
}

输出(一部分)是:
线程2调用了g174次
线程2调用了g175次
线程2调用了g176次
线程2调用了g177次
线程2调用了g178次
线程2调用了g179次
线程2调用了g180次
线程2调用了g181次
线程2调用了g182次
线程2调用了g183次
线程2调用了g184次
线程1调用了f1次
线程1调用了f2次
线程1调用了f3次
线程1调用了f4次
线程1调用了f5次
线程1调用了f6次
线程1调用了f7次
线程1调用了f8次

为什么线程2还没有执行外线程1就开始执行了?
另外,明明线程1先执行的statr()方法呀,为啥线程2先执行?


跪求高手解释
...全文

相关推荐

评论 5
收藏 已收藏
分享
返回顶部
xiaoning_131
Java EE 67,535 成员 225,843 内容