同步与死锁

本文通过示例介绍了如何使用synchronized关键字实现Java多线程中的资源共享,并讨论了同步代码块和同步方法的使用方式,同时提到了过度同步可能导致的死锁问题。

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

使用runnable可以将资源共享,但是在延迟时,还是会出现错误:


class MyThread implements Runnable

{
    private int iTickets = 5 ;
    public void run(){
        for(int i=0;i<100;i++){
            if(iTickets > 0){
                try{
                    Thread.sleep(300) ;
                }catch(InterruptedException e){
                    e.printStackTrace() ;
                }
                System.out.println("卖票:" + iTickets--) ;
            }
        }
    }
};
public class SyncDemo01
{
    public static void main(String args[]){
        MyThread mt1 = new MyThread() ;
        Thread t1 = new Thread(mt1) ;
        Thread t2 = new Thread(mt1) ;
        Thread t3 = new Thread(mt1) ;
        t1.start() ;
        t2.start() ;
        t3.start() ;
    }

}

同步代码块:

synchronized(需同步的对象){

同步代码块;

}

※同步对象通常用this表示

class MyThread implements Runnable
{
    private int iTickets = 5 ;
    public void run(){
        for(int i=0;i<100;i++){
            synchronized(this){
                if(iTickets > 0){
                    try{
                        Thread.sleep(300) ;
                    }catch(InterruptedException e){
                        e.printStackTrace() ;
                    }
                    System.out.println("卖票:" + iTickets--) ;
                }
            }
        }
    }
};
public class SyncDemo02
{
    public static void main(String args[]){
        MyThread mt1 = new MyThread() ;
        Thread t1 = new Thread(mt1) ;
        Thread t2 = new Thread(mt1) ;
        Thread t3 = new Thread(mt1) ;
        t1.start() ;
        t2.start() ;
        t3.start() ;
    }
}

可以使用synchronized关键字将方法声明成同步方法

格式:synchronized    方法返回值  方法名称(参数列表){}


二、死锁

资源共享式需要进行同步

程序中过多的同步会产生死锁




评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值