Java多线程与并发——死锁与中断线程
2024-08-28 16:33:31
过多的同步有可能出现死锁,死锁的操作一般是在程序运行的时候才有可能出现。
多线程中要进行资源的共享,就需要同步,但同步过多,就可能造成死锁。
死锁例子:
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;//退出循环
}
} }
}
最新文章
- MFC 按钮如何改变颜色
- ASP.NET corrupt assembly “Could not load file or assembly App_Web_*
- SolrCloud环境配置
- Spring切入点表达式常用写法
- 细说Java多线程之内存可见性
- [MSDN]使用 REST 处理文件夹和文件
- uva 10986 - Sending email(最短路Dijkstra)
- Mysql 常用查询语句
- 【NO.4】jmeter-cookie管理器
- Linux-fdisk磁盘分区命令(16)
- 原生JS实现淘宝无缝轮播
- How Classes are Found
- Sitecore8.2 Solr5.1.0配置步骤
- 如何使用Shell判断版本号的大小
- [20170705]diff比较执行结果的内容.txt
- hbase与hive集成:hive读取hbase中数据
- JSP Servlet学习笔记——使用fileupload上传文件
- win10如何彻底删除Gis|彻底卸载ArcGis的方法说明
- Stored Properties 与 Computed Properties
- widnows 使用WIN32 APi 实现修改另一打开程序的窗口显示方式