多个操做在同一时间内 只能有一个线程运行,其余线程要等此线程完成以后才能继续执行。
要解决资源共享的同步操做问题,能够使用同步代码块和同步方法完成。
1.1 同步代码块
代码块分四种:
(1) 普通代码块:是直接定义在方法之中的。
(2)构造块:是定义在类中的,优先于构造方法执行,能够重复调用
(3)静态块:是使用static关键字声明,又相遇构造块执行,只执行一次
(4)同步代码块:使用synchronized关键字声明,为同步代码块
格式this
synchronized(同步对象)//当前对象做为同步对象 使用this表示{ 须要同步的代码 }
class MyThread implements Runnable {public int ticket = 5 ; //定义票的数量public void run() //覆写run()方法{for(int i=0;i<100;i++) { synchronized(this) //同步代码块 对当前对象进行同步{if(ticket>0) //若是还有票{try{ Thread.sleep(2000) ;//时间延迟}catch (InterruptedException e) { e.printStackTrace() ; } System.out.println("卖票 ticket:"+ ticket--) ; } } } } }public class SyncDemo01 {public static void main(String[] args) { MyThread mt = new MyThread() ;//实例化线程对象Thread t1 = new Thread(mt) ; //定义Thread对象Thread t2 = new Thread(mt) ; //定义Thread对象Thread t3 = new Thread(mt) ; //定义第三个售票员t1.start() ; //启动线程t2.start() ; //开始卖票t3.start() ; //启动线程} }
使用同步操做,不会出现负数,可是程序执行效果降低
1.2 同步方法
使用synchronized关键字将一个方法声明成同步方法
格式spa
synchronized 方法返回值 方法名称(参数列表){}
class MyThread implements Runnable {public int ticket = 5 ; //定义票的数量public void run() //覆写run()方法{for(int i=0;i<100;i++) { this.sale() ; //调用同步方法} }public synchronized void sale() //声明同步方法 卖票{if(ticket>0) //若是还有票{try{ Thread.sleep(2000) ; }catch (InterruptedException e) { e.printStackTrace() ; } System.out.println("卖票 ticket:"+ ticket--) ; } } }public class SyncDemo02 {public static void main(String[] args) { MyThread mt = new MyThread() ;//实例化线程对象Thread t1 = new Thread(mt) ; //定义Thread对象Thread t2 = new Thread(mt) ; //定义Thread对象Thread t3 = new Thread(mt) ; //定义第三个售票员t1.start() ; //启动线程t2.start() ; //开始卖票t3.start() ; //启动线程} }
A 资源共享的时候须要进行同步操做
B 程序中过多的同步会产生死锁
死锁 通常状况下就是表示 在互相等待 。线程
修改标记位 来 中止线程code
class MyThread implements Runnable {private boolean flag = true ; //定义标记位public void run() //覆写run()方法{int i = 0 ;while(this.flag) //this表示当前对象{ System.out.println(Thread.currentThread().getName() +"运行,i"+(i++)) ; } }public void stop() //定义stop方法{this.flag = false ; //修改标记位} }public class ThreadStopDemo01 {public static void main(String[] args) { MyThread mt = new MyThread() ; //实例化MyThread对象Thread t = new Thread(mt,"当前线程名称") ; //声明Thread线程对象t.start() ; //启动线程try{ Thread.sleep(30) ; }catch (InterruptedException e) { e.printStackTrace() ; } mt.stop() ; //中止线程 //对象.方法()} }