多线程同步基础
主线程执行完要等待其他线程执行完,才退出虚拟机
主线程执行完需要让其他线程也结束,可设置为守护线程,守护线程必须在线程启动前开启
实现方式和继承方式的区别:
实现方式好处避免了但继承的局限性(不能继承其他类,只能继承Thread类)
定义线程时,建议使用实现方式。
两种方式区别:
继承Thread:线程代码存放Thread子类的run方法中
实现Runnable:线程代码存放接口子类的run方法中
同步的前提:
1,必须要有两个或者两个以上的线程。
2,必须是多个线程使用同一个锁(同一个对象)。
必须保证同步中只能有一个线程在运行。
如何判断程序是否有安全问题:
1,明确哪些代码是多线程运行代码。
2,明确共享数据。
3,明确多线程运行代码中哪些语句是操作共享数据的。
同步的两种表现形式:同步代码块和同步函数
同步代码块
Objectobj=newObject();synchronized(obj){//todo}
同步函数(使用的锁是this)
同步函数被静态修饰后使用的锁不再是this,因为静态方法中不可以有this,
静态的同步方法使用的锁是该方法所在类的字节码文件对象。 类名.class
publicsynchronizedvoidadd(intn){}
publicstaticsynchronizedvoidshow(){}
同步代码块和同步函数要使用同一把锁需要让同步代码块的锁设为this或者类名.class
多线程单例最好写成饿汉式(函数里面只有一句话)
classSingle{privatestaticfinalSingles=newSingle();privateSingle(){}publicstaticSinglegetInstance(){returns;}}
懒汉式的延时加载多线程访问时会出现安全问题,同步锁是该类的字节码对象
classSingle{privatestaticSingles=null;privateSingle(){}publicstaticSinglegetInstance(){if(s==null){synchronized(Single.class){if(s==null)//--->A;s=newSingle();}}returns;}}
同步弊端死锁-同步嵌套,锁不一样
/*死锁。同步中嵌套同步。*/classTicketimplementsRunnable{privateinttick=1000;Objectobj=newObject();booleanflag=true;publicvoidrun(){if(flag){while(true){synchronized(obj){show();}}}elsewhile(true)show();}publicsynchronizedvoidshow()//this{synchronized(obj){if(tick>0){try{Thread.sleep(10);}catch(Exceptione){}System.out.println(Thread.currentThread().getName()+"....code:"+tick--);}}}}classDeadLockDemo{publicstaticvoidmain(String[]args){Tickett=newTicket();Threadt1=newThread(t);Threadt2=newThread(t);t1.start();try{Thread.sleep(10);}catch(Exceptione){}t.flag=false;t2.start();}}
classTestimplementsRunnable{privatebooleanflag;Test(booleanflag){this.flag=flag;}publicvoidrun(){if(flag){while(true){synchronized(MyLock.locka){System.out.println(Thread.currentThread().getName()+"...iflocka");synchronized(MyLock.lockb){System.out.println(Thread.currentThread().getName()+"..iflockb");}}}}else{while(true){synchronized(MyLock.lockb){System.out.println(Thread.currentThread().getName()+"..elselockb");synchronized(MyLock.locka){System.out.println(Thread.currentThread().getName()+".....elselocka");}}}}}}classMyLock{staticObjectlocka=newObject();staticObjectlockb=newObject();}classDeadLockTest{publicstaticvoidmain(String[]args){Threadt1=newThread(newTest(true));Threadt2=newThread(newTest(false));t1.start();t2.start();}}
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。