过多的同步有可能出现死锁,死锁的操作一般是在程序运行的时候才有可能出现。

多线程中要进行资源的共享,就需要同步,但同步过多,就可能造成死锁。

死锁例子:

package com.vince;
/**
* 线程死锁
* @author acer
*
*/
public class DeadThreadDemo { public static void main(String[] args) {
new DeadThread(); } } //顾客
class Customer{
public synchronized void say(Waiter w){
System.out.println("顾客说,先吃饭在买单");
w.doService();
}
public synchronized void doService(){
System.out.println("同意了,买完单在吃饭");
}
} //服务生
class Waiter{
public synchronized void say(Customer c){
System.out.println("服务员说,先买单在吃饭");
c.doService();
}
public synchronized void doService(){
System.out.println("同意了,吃完饭在买单");
}
} //死锁线程
class DeadThread implements Runnable{
Customer c=new Customer();
Waiter w=new Waiter();
public DeadThread(){
new Thread(this).start();
w.say(c);
}
public void run() {
c.say(w); } }

中断线程例子:

package com.vince;

/**
* 中断线程,自定义标记
* @author acer
*
*/
public class ThreadDemo { public static void main(String[] args) {
MyThread mt=new MyThread();
Thread t1=new Thread(mt);
t1.start();
//t1.stop();//停止
for(int i=0;i<10;i++){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
mt.flag=false;
} static class MyThread implements Runnable{
public boolean flag;
public MyThread(){
flag=true;
}
public void run() {
int i=0;
while(flag){
System.out.println("i="+i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
i++;
if(i==100) break;//退出循环
}
} }
}

最新文章

  1. MFC 按钮如何改变颜色
  2. ASP.NET corrupt assembly “Could not load file or assembly App_Web_*
  3. SolrCloud环境配置
  4. Spring切入点表达式常用写法
  5. 细说Java多线程之内存可见性
  6. [MSDN]使用 REST 处理文件夹和文件
  7. uva 10986 - Sending email(最短路Dijkstra)
  8. Mysql 常用查询语句
  9. 【NO.4】jmeter-cookie管理器
  10. Linux-fdisk磁盘分区命令(16)
  11. 原生JS实现淘宝无缝轮播
  12. How Classes are Found
  13. Sitecore8.2 Solr5.1.0配置步骤
  14. 如何使用Shell判断版本号的大小
  15. [20170705]diff比较执行结果的内容.txt
  16. hbase与hive集成:hive读取hbase中数据
  17. JSP Servlet学习笔记——使用fileupload上传文件
  18. win10如何彻底删除Gis|彻底卸载ArcGis的方法说明
  19. Stored Properties 与 Computed Properties
  20. widnows 使用WIN32 APi 实现修改另一打开程序的窗口显示方式

热门文章

  1. python 3中对list进行sort时,返回值为None
  2. 三、使用maven创建scala工程(scala和java混一起)
  3. JVM体系结构之六:堆Heap之1
  4. MySQL(介绍1)
  5. SQL Server BCP 资料导入导出
  6. CentOS安装配置radius服务器
  7. SVD实例
  8. tar 排除某个目录
  9. sharepoint Foundation 2013 error
  10. 查看Linux、Tomcat、JAVA版本信息