java 同步函数

1.明确哪些代码是多线程代。

2.明确共享数据。

3.明确多线程运行代码中哪些语句是操作共享数据的。

synchronized作为修饰符放函数上。
同步函数使用的锁是:this
验证:开启两个线程,一个同步代码块,一个同步函数。
class Ticket implements Runnable {
    private int tick = 100;
    boolean flag = true;
    @Override
    public void run() {
        if (flag) {
            while (true) {
                synchronized (this) {
                    if (tick > 0) {
                        try {
                            Thread.sleep(10);
                        } catch (InterruptedException e) {
                        }
                        System.out.println(Thread.currentThread().getName() + "...code:" + tick--);
                    }
                }
            }
        }else while (true)
            show();
    }

    public synchronized void show() {
        if (tick > 0) {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
            }
            System.out.println(Thread.currentThread().getName() + "...show():" + tick--);
        }
    }
}

public class Demo {
    public static void main(String[] args) {
        Ticket t = new Ticket();
        Thread t1 = new Thread(t);
        Thread t2 = new Thread(t);
        t1.start();
        try {
            Thread.sleep(10);
        }catch (InterruptedException e){

        }
        t.flag=false;
        t2.start();
    }
}
 

this才能保证程序正常运行。

this指向当前对象,但是如果是静态呢?静态的时候还没有创建对象,也就不存在this,那么静态函数中的锁是什么呢?字节码文件对象:类名.class

 
class Ticket implements Runnable {
    private static int tick = 100;
    boolean flag = true;
    @Override
    public void run() {
        if (flag) {
            while (true) {
                synchronized (Ticket.class) {
                    if (tick > 0) {
                        try {
                            Thread.sleep(10);
                        } catch (InterruptedException e) {
                        }
                        System.out.println(Thread.currentThread().getName() + "...code:" + tick--);
                    }
                }
            }
        }else while (true)
            show();
    }

    public static synchronized void show() {
        if (tick > 0) {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
            }
            System.out.println(Thread.currentThread().getName() + "...show():" + tick--);
        }
    }
}

public class Demo {
    public static void main(String[] args) {
        Ticket t = new Ticket();
        Thread t1 = new Thread(t);
        Thread t2 = new Thread(t);
        t1.start();
        try {
            Thread.sleep(10);
        }catch (InterruptedException e){

        }
        t.flag=false;
        t2.start();
    }
}
 

 

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值