/*
@author Kallen Ding
Which is the Lock of Synchronized Function?
Each function needs a object to be called,
so every function has a reference of its
object,which called this lock.
Consequently,the lock of Synchronized Function
is this.
Test:
Using two threads to execute the program,
one running in synchronized code,the other
running in sychronized function.
*/
class Ticket implements Runnable
{
private int tick = 1000;
Object obj = new Object();
boolean flag = true;
public void run()
{
if(flag)
{
while(true)
{
synchronized(obj)
{
if(tick>0)
{
//try{Thread.sleep(10);}
//catch(Exception e){}
System.out.println(
Thread.currentThread().
getName()+"------SyncCodes:"
+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()+"------SyncFunction:"
+tick--);
}
}
}
class ThisLockDemo2
{
public static void main(String[] args)
{
Ticket t = new Ticket();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
t1.start();
t.flag = false;
t2.start();
}
}
多线程(四)——多线程安全问题之同步函数(This Lock )
最新推荐文章于 2023-04-28 10:00:00 发布