同步synchronized 示例 和 理解(未完,先把代码copy上,过会在写注释和理解)

本文通过一个Java多线程示例展示了如何使用synchronized关键字实现线程间的同步操作,确保共享资源的安全访问。两个线程分别通过TestMath1和TestMath2类实例化并启动,它们共享同一个Maths类的实例,该类包含了一个同步方法execute来控制对共享变量的访问。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


public class TestThread {
 
 public static void main( String[] args ) {
  TestMath1 tm = new TestMath1();
  new Thread ( tm , "TestMath1" ).start();
  new Thread ( tm , "TestMath2" ).start();
//  TestMath2 tm2 = new TestMath2();
//  new Thread ( tm2 , "TestMath2" ).start();
 }

}

class TestMath1 implements Runnable {
 public void run() {
  new Maths().execute( this );
 }
}

class TestMath2 implements Runnable {
 public void run() {
  new Maths().execute( this );
 }
}

class Maths {
 /*
 static Object o = new Object();
 
 public void execute() {
  synchronized( o ) {//同步锁,用于锁住当前类实例,知道执行完毕解锁
   int i = 0;
   while ( i < 20 ) {
    System.out.println( Thread.currentThread().getName()+":"+ i );
    i++;
   }
  }
 }
 public synchronized void execute() {
  int i = 0;
  while ( i < 20 ) {
   System.out.println( Thread.currentThread().getName()+":"+ i );
   i++;
  }
 }
 
 public void execute() {
  synchronized( this ) {
   int i = 0;
   while ( i < 20 ) {
    System.out.println( Thread.currentThread().getName()+":"+ i );
    i++;
   }
  }
 }*/
 
 public void execute( Object o ) {
  synchronized( o ) {
   int i = 0;
   while ( i < 20 ) {
    System.out.println( Thread.currentThread().getName()+":"+ i );
    i++;
   }
  }
 }
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值