[知了堂学习笔记]_线程同步

请关注“知了堂学习社区”,地址:http://www.zhiliaotang.com/portal.php

锁:保护资源—-资源:卫生间、线程:上卫生间的人、锁:卫生间的门
一把锁只有一把钥匙
只有执行完被锁住的程序块钥匙才能被释放
锁保护谁:成员属性/静态成员属性
锁有几种:this—-当前对象的锁

package thread;

public class Thread_6 {

    /**
     * @param args
     */
    public static void main(String[] args) {

        final Method m = new Method();
        Thread t1 = new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                m.m1();
            }
        });
        Thread t2 = new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                m.m2();
            }
        });
        t1.start();
        t2.start();
    }

}
class Method{
    public void m1(){
        synchronized (this) {
            for(int i=0;i<5;i++){
                System.out.println(Thread.currentThread().getName()+" "+i);
            }
        }
    }
    public void m2(){
        synchronized (this) {
            for(int i=0;i<5;i++){
                System.out.println(Thread.currentThread().getName()+" "+i);
            }
        }
    }
}

类.class—-当前类的class对象的锁
成员属性
方法上加锁—-锁就是this对象的锁
静态方法加锁—-class实例的锁
锁属于谁:
锁是属于对象的
每一个对象都有一把唯一的锁

package thread;

public class Thread_5 {

    /**
     * @param args
     */
    public static void main(String[] args) {

        SaleTask sale = new SaleTask();
        Thread t1 = new Thread(sale);
        t1.setName("网络");
        Thread t2 = new Thread(sale);
        t2.setName("电话");
        Thread t3 = new Thread(sale);
        t3.setName("现场");
        t1.start();
        t2.start();
        t3.start();
    }

}
class SaleTask implements Runnable{

    int id = 100;
    @Override
    public void run() {
        while(true){
            synchronized (this) {//t1,t2,t3拿到钥匙,且只有一把钥匙
                if(id>0){
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    System.out.println("卖票"+id--);
                }else{
                    System.out.println("票卖完");
                    break;
                }
            }//运行到这里归还钥匙
        }

    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值