java多线程学习(二)

来源:互联网 发布:杭州皓辰网络法人 编辑:程序博客网 时间:2024/06/05 19:21

同步函数

同步函数:在函数上加上了同步关键字synchronized进行修饰。
同步表现形式:1.同步代码块 2.同步函数
同步函数例子:

class Bank{    private int sum;    //private Object obj=new Object();    public synchronized void add(int n)    {        //synchronized(obj)注释部分为同步代码块        //{            sum=sum+n;            try{Thread.sleep(10);}catch(Exception e){}//让线程在这稍微停一下            System.out.println("sum="+sum);        //}    }}class Customer implements Runnable{    private Bank b=new Bank();    public void run()    {        for(int x=0;x<3;x++)        {            b.add(100);        }    }}

同步函数使用的锁是什么?
函数需要被调用,哪个对象不确定,但是都用this来表示,同步函数使用的锁就是this。

如果同步函数被static修饰呢?
static方法随着类加载,这时不一定有该类的对象,但是一定有一个该类的字节码文件对象,这个对象简单的表示方式就是:类名.class Class
举例部分代码:

while(true){     synchronized(SaleTicket.class)//类名.class     {         if(tickets>0)         {             try{Thread.sleep(10);}catch(Exception e){}//让线程在这稍微停一下             Sysytem.out.println(Thread.currentThread.getName()+"..."+tickets--);        }   }}