您的位置:首页 > 其它

基础篇_线程 第5集 多线程的安全问题--解决之道同步函数

2016-05-05 00:01 531 查看
同步函数--卖票示例

同步函数用是哪一个锁呢??---this

函数需要被对象调用。那么函数都有一个所属对象引用。就是this。

通过该程序进行验证。

使用两个线程来卖票。

一个线程在同步函数中,一个在同步代码块中。

都在执行卖票动作。

class Ticket2 implements Runnable //extends Thread
{
private int tick=100;
Object obj=new Object();
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()//同步函数用的锁是哪一个呢?this
{
if(tick>0)
{
try {Thread.sleep(10);}
catch (Exception e) {}
System.out.println(Thread.currentThread().getName()+" show "+tick--);
}
}

}

public class ThisLockDemo {

public static void main(String[] args) {

Ticket2 t=new Ticket2();

Thread t1=new Thread(t);//创建了一个线程
Thread t2=new Thread(t);//创建了一个线程
//		Thread t3=new Thread(t);//创建了一个线程
//		Thread t4=new Thread(t);//创建了一个线程

t1.start();
try {Thread.sleep(10);}
catch (Exception e){}

t.flag=false;
t2.start();
//		t3.start();
//		t4.start();
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: