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

来源:互联网 发布:asp.net连接数据库 编辑:程序博客网 时间:2024/06/10 22:28
同步函数--卖票示例

同步函数用是哪一个锁呢??---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--);}}}}elsewhile(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();}}


0 0
原创粉丝点击