Java笔记 - 多线程-同步函数

来源:互联网 发布:淘宝会员号 编辑:程序博客网 时间:2024/05/17 23:41


synchronized写在函数的前面


class Bank{private int sum;public synchronized void add(int n){sum = sum + n;try{Thread.sleep(10);}catch(Exception e){}System.out.println("sum=" + sum);}}class Cus implements Runnable{private Bank b = new Bank();public void run(){for(int x=0; x<3; x++){b.add(100);}}}public class BankDemo {public static void main(String[] args){Cus c = new Cus();Thread t1 = new Thread(c);Thread t2 = new Thread(c);t1.start();t2.start();}}


同步函数使用的锁是this



class Ticket implements Runnable{private int tick = 100;boolean flag = true;public void run(){if(flag){while(true){synchronized(this){if(tick>0){try{Thread.sleep(10);}catch(Exception 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(Exception e){System.out.println(Thread.currentThread().getName()+"..show.."+tick--);}}}}public class staticMethodDemo {public static void main(String[] args){Ticket t = new Ticket();Thread t1 = new Thread(t);Thread t2 = new Thread(t);t1.start();t2.start();}}


如果同步函数被静态修饰后,使用的锁是什么?

通过验证,发现不是this,因为静态方法中也不可以定义this。

静态进内存是,内存中没有本类对象,但是一定有该类对应的字节码文件对象。

类名.class 该对象的类型是Class


静态的同步方法,使用的锁是该方法所在类的字节码文件对象。 类型.class


class Ticket implements Runnable{private static int tick = 100;boolean flag = true;public void run(){if(flag){while(true){synchronized(Ticket.class){if(tick>0){try{Thread.sleep(10);}catch(Exception 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(Exception e){System.out.println(Thread.currentThread().getName()+"..show.."+tick--);}}}}public class staticMethodDemo {public static void main(String[] args){Ticket t = new Ticket();Thread t1 = new Thread(t);Thread t2 = new Thread(t);t1.start();t2.start();}}




0 0
原创粉丝点击