/*
@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 发布
本文探讨了同步函数的概念及其在多线程编程中的锁机制实现,通过实例展示了如何使用同步函数确保线程间的正确交互与资源访问顺序。详细介绍了线程之间的协作与竞争情况,以及如何利用同步函数避免常见的并发问题。
10万+

被折叠的 条评论
为什么被折叠?



