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();
    }
}
 
 
 

猜你喜欢

转载自www.cnblogs.com/hongxiao2020/p/12589009.html