多线程 同步与死锁
2016-04-12 00:00
330 查看
1.1 同步
多个操作在同一时间内 只能有一个线程运行,其他线程要等此线程完成之后才能继续执行。要解决资源共享的同步操作问题,可以使用同步代码块和同步方法完成。
1.1 同步代码块
代码块分四种:
(1) 普通代码块:是直接定义在方法之中的。
(2)构造块:是定义在类中的,优先于构造方法执行,可以重复调用
(3)静态块:是使用static关键字声明,又相遇构造块执行,只执行一次
(4)同步代码块:使用synchronized关键字声明,为同步代码块
格式
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关键字将一个方法声明成同步方法
格式
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() ; //启动线程} }
2 死锁
A 资源共享的时候需要进行同步操作B 程序中过多的同步会产生死锁
死锁 一般情况下就是表示 在互相等待 。
3线程生命周期
修改标记位 来 停止线程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() ; //停止线程 //对象.方法()} }
相关文章推荐
- UAF学习记录
- Spring IOC(自整)
- JAVA生成网页图片验证码
- emacs中完成c++程序编译执行
- 简单的Jax-WS WebService实现
- 插件安装
- IQKeyboardManager
- PHP中实现代码复用的Trait方法的一些特性
- eclipse常用设置
- Linux下源码安装PostgreSql和PostGIS
- javascript排序算法
- C#入门
- C# chart控件绘制多图表区图像
- stm32笔记:GPIO的的配置和操作(1)推挽输出方式
- Hive从零起步
- Hadoop2.4.1伪分布式搭建
- tomcat和eclipse集成
- Try catch使用模板
- 无法在Word中打开MathType怎么办
- MathType公式保存后为什么字体会变化