synchronized读写锁和多线程处理

本文通过两个示例详细探讨了Java中的synchronized关键字如何实现线程间的同步操作,包括使用synchronized修改变量值的线程安全性及synchronized方法的锁机制。通过具体代码展示了在多线程环境下synchronized如何避免数据竞争条件,确保数据的一致性和完整性。

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

synchronized的操作如https://blog.youkuaiyun.com/zjy15203167987/article/details/82531772

1、public class SyncTest implements Runnable{
static int i = 0;
public synchronized void increase(){
//System.out.println(i);
i++;
}

@Override
public void run() {
    for(int j=0;j<10000;j++){
        increase();
    }
}

public static void main(String[] args) throws InterruptedException {
    SyncTest syncTest = new SyncTest();
    Thread thread1 = new Thread(syncTest);
    Thread thread2 = new Thread(syncTest);
    thread1.start();
    thread2.start();
    thread1.join();
    thread2.join();
    System.out.println(i);
}

}

2、public class SyncTest2 {
public synchronized void method1(){
System.out.println(“method1 start”);
try {
System.out.println(“method1 execute”);
Thread.sleep(3000);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(“method1 end”);
}

public synchronized  void method2(){
    System.out.println("method2 start");
    try {
        System.out.println("method2 execute");
        Thread.sleep(1000);
    } catch (Exception e) {
        e.printStackTrace();
    }
    System.out.println("method2 end");
}

public static void main(String[] args) {
     SyncTest2 test = new SyncTest2();
     new Thread(new Runnable() {
         @Override
         public void run() {
             test.method1();
         }
     }).start();

    new Thread(new Runnable() {
        @Override
        public void run() {
            test.method2();
        }
    }).start();
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值