java synchronized详解--synchronized代码块

本文详细探讨了Java中的`synchronized`关键字,通过三个场景分析了其使用方式和效果。第一种场景不加锁导致线程并发执行。第二种场景中,由于每个线程使用不同的锁对象,锁并未生效。而在第三种场景中,两个线程共享同一锁对象,实现了线程同步。总结指出,正确使用`synchronized`需确保所有线程使用相同的锁对象,以实现资源的互斥访问。
摘要由CSDN通过智能技术生成

synchronized详解

回想起来,代码中一直用synchronized了,但是好像对它理解不到位,今天抓点时间复习一下。写了几个代码例子说明一下。

结构简述:

定义了一个资源PrintDemo,一个线程类ThreadDemo,一个测试类TestThread,在测试类中创建两个线程对象,两个线程对象都通过run方法访问资源PrintDemo.printCount方法

第一种场景:不对资源加锁
package com.yy.test;

/**
 * Created by skyler on 2017/2/17.
 */
class PrintDemo {
    public void printCount() {
        try {
            for(int i = 10; i > 0; i--) {
                System.out.println("Counter   ---   "  + i );
            }
        }catch (Exception e) {
            System.out.println("Thread  interrupted.");
        }
    }
}

class ThreadDemo extends Thread {
    private Thread t;
    private String threadName;
    PrintDemo  PD;

    ThreadDemo( String name,  PrintDemo pd) {
        threadName = name;
        PD = pd;
    }

    public void run() {
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        PD.printCount();
        System.out.println("Thread " +  threadName + " exiting.");
    }

    public void start () {
        System.out.println("Starting " +  threadName );
        if (t == null) {
            t = new Thread (this, threadName);
            t.start ();
        }
    }
}

public class TestThread {
   
    public static void main(String args[]) {
       TestThread tt = new TestThread();
       tt.test1();
    }
    public void test1() {
        PrintDemo2 PD = new PrintDemo2();

        ThreadDemo2 T1 = new ThreadDemo2( "Thread - 1 ", PD );
        ThreadDemo2 T2 = new ThreadDemo2( "Thread - 2 ", PD );

        T1.start();
        T2.start();

        // wait for threads to end
        try {
            T1.join();
            T2.join();
        }catch( Exception e) {
            System.out.println("Interrupted");
        }
    }
}

运行结果:
Starting Thread - 1 
Starting Thread - 2 
Counter   ---   10
Counter   ---   10
Counter   ---   9
Counter   ---   9
Counter   ---   8
Counter   ---   8
Counter   ---   7
Counter   ---   6
Counter   ---   5
Counter   ---   4
Counter   ---   3
Counter   ---   2
Counter   -
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值