java 线程 被相互排斥堵塞、检查中断演示样例解说----thinking java4
package org.rui.thread.block; /**
* 被相互排斥堵塞 就像在interrupting.java中看到的,假设你偿试着在一个对象上调用其synchronized方法,
* 而这个对象的锁已经被其它任务获得,那么调用任务将被挂起(堵塞) ,直至这个锁可获得.
* 以下的演示样例说明了同一个相互排斥能够怎样能被同一个任务多次获得
*
* @author lenovo
*
*/
public class MultiLock {
public synchronized void f1(int count) {
if (count-- > 0) {
System.out.println("f1() calling f2() with count " + count);
f2(count);
}
} public synchronized void f2(int count){
if(count-->0){
System.out.println("f2() calling f1() with count "+count);
f1(count);
}
} public static void main(String[] args) {
final MultiLock multiLock=new MultiLock();
new Thread(){
public void run(){
multiLock.f1(10);
}
}.start();
}
}
/**OUTPUT:
f1() calling f2() with count 9
f2() calling f1() with count 8
f1() calling f2() with count 7
f2() calling f1() with count 6
f1() calling f2() with count 5
f2() calling f1() with count 4
f1() calling f2() with count 3
f2() calling f1() with count 2
f1() calling f2() with count 1
f2() calling f1() with count 0
*/
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvbGlhbmdydWkxOTg4/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="">
package org.rui.thread.block; import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock; //Mutex 相互排斥 Reentrant :可重入
class BlockedMutex {
private Lock lock = new ReentrantLock(); public BlockedMutex() {
// Acquire it reght away, to demonstrate interruption 获取它心中,来演示中断
// of a task blocked on a ReentrantLock reentrantLock的任务了
lock.lock();
} public void f() {
try {
// this will nerer be available to a second task 这将纵然是可用的第二个任务
lock.lockInterruptibly();// 假设当前线程未被中断,则获取锁 special call
System.out.println("lock acquired in f()");
} catch (InterruptedException e) {
System.out.println("interrupted from lock acuisition in f()");
}
}
} class Blocked2 implements Runnable {
BlockedMutex blocked = new BlockedMutex(); @Override
public void run() {
System.out.println("Waiting for f() in BlockedMutex");
blocked.f();
System.out.println("Broken out of blocked call");//爆发的堵塞调用 } } public class Interruptiing2 {
public static void main(String[] args) throws InterruptedException {
Thread t=new Thread(new Blocked2());
t.start();
TimeUnit.SECONDS.sleep(1);
System.out.println("Issuing t.interrupt()");
//t.interrupt();//中断线程
}
}
/**
* output:
Waiting for f() in BlockedMutex
Issuing t.interrupt()
interrupted from lock acuisition in f()
Broken out of blocked call
*/
package org.rui.thread.block; import java.util.concurrent.TimeUnit;
/**
* 检查中断
* @author lenovo
*
*/
class NeedsCleanup {//须要清除
private final int id; public NeedsCleanup(int ident) {
id = ident;
System.out.println("NeedsCleanup " + id);
} public void cleanup() {
System.out.println("Cleaning up " + id);
}
} class Blocked3 implements Runnable {
private volatile double d = 0.0; public void run() {
try {
while (!Thread.interrupted()) {
// point1
NeedsCleanup n1 = new NeedsCleanup(1);
// start try-finally immediately after definition
// of n1 , to auarantee proper cleanup of n1
try {
System.out.println("sleeping");
TimeUnit.SECONDS.sleep(1);
// point 2
NeedsCleanup n2 = new NeedsCleanup(2);
// guarantee proper cleanup of n2 保证适当的清理n2
try {
System.out.println("计算单元");
// A time-consuming,non-blocking operation: 耗时,非堵塞操作
for (int i = 1; i < 2500000; i++) {
d = d + (Math.PI + Math.E) / d;
}
System.out.println("完毕耗时的操作");
} finally {
n2.cleanup();
} } finally {
n1.cleanup();
//throw new InterruptedException();
}
}
System.out.println("exiting via while() test");
} catch (InterruptedException e) {
System.out.println("exiting via inerruptedExecption");
}
}
} // ///////////////////////////////////// public class InterruptingIdiom { public static void main(String[] args) throws Exception {
String[] arg = { "1100" };
if (arg.length != 1) {
System.exit(1);
}
Thread t = new Thread(new Blocked3());
t.start();
TimeUnit.MILLISECONDS.sleep(new Integer(arg[0]));
t.interrupt();
}
}
/**
output: NeedsCleanup 1
sleeping
NeedsCleanup 2
计算单元
完毕耗时的操作
Cleaning up 2
Cleaning up 1
NeedsCleanup 1
sleeping
Cleaning up 1
exiting via inerruptedExecption
*/
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvbGlhbmdydWkxOTg4/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="">
java 线程 被相互排斥堵塞、检查中断演示样例解说----thinking java4的更多相关文章
- java 又一次抛出异常 相关处理结果演示样例代码
java 又一次抛出异常 相关处理结果演示样例代码 package org.rui.ExceptionTest; /** * 又一次抛出异常 * 在某些情况下,我们想又一次掷出刚才产生过的违例,特别是 ...
- java 线程 原子类相关操作演示样例 thinking in java4 文件夹21.3.4
java 线程 原子类相关操作演示样例 package org.rui.thread.volatiles; import java.util.Timer; import java.util.Time ...
- linux系统编程:线程同步-相互排斥量(mutex)
线程同步-相互排斥量(mutex) 线程同步 多个线程同一时候訪问共享数据时可能会冲突,于是须要实现线程同步. 一个线程冲突的演示样例 #include <stdio.h> #includ ...
- java 线程、线程池基本应用演示样例代码回想
java 线程.线程池基本应用演示样例代码回想 package org.rui.thread; /** * 定义任务 * * @author lenovo * */ public class Lift ...
- Java线程演示样例 - 继承Thread类和实现Runnable接口
进程(Process)和线程(Thread)是程序执行的两个基本单元. Java并发编程很多其它的是和线程相关. 进程 进程是一个独立的执行单元,可将其视为一个程序或应用.然而,一个程序内部同事还包括 ...
- Java多线程演示样例(模拟通话,sleep,join,yield,wait,notify,Semaphore)
主线程等待子线程的多种方法 synchronized浅析 sleep 是静态方法,Thread.sleep(xx)谁调用谁睡眠. join 是合并方法.当前线程调用其它线程xx.join()则等到xx ...
- java 覆盖hashCode()深入探讨 代码演示样例
java 翻盖hashCode()深入探讨 代码演示样例 package org.rui.collection2.hashcode; /** * 覆盖hashcode * 设计HashCode时最重要 ...
- Java 8 时间日期库的20个使用演示样例
除了lambda表达式,stream以及几个小的改进之外,Java 8还引入了一套全新的时间日期API,在本篇教程中我们将通过几个简单的任务演示样例来学习怎样使用Java 8的这套API.Java对日 ...
- HBase总结(十一)hbase Java API 介绍及使用演示样例
几个相关类与HBase数据模型之间的相应关系 java类 HBase数据模型 HBaseAdmin 数据库(DataBase) HBaseConfiguration HTable 表(Table) H ...
随机推荐
- gradients的一些注意点
Each variable has a [.grad_fn] attribute that references a Function that has created the Variable(ex ...
- 你值得关注的几种常见的js设计模式
前言 潜水了一段时间,今天空闲时间复盘下之前的知识点,聊聊 js 几种常见的设计模式. 掌握 JavaScript 中常见的一些设计模式,对我们书写规范性代码,可维护性代码有很大的帮助. ps:最近在 ...
- MySQL Workbench关键字转成小写设置
- Spring MVC的各种参数绑定方式(请求参数用基础类型和包装类型的区别)(转)
1.基本数据类型(以int为例,其他类似): Controller代码: @RequestMapping("saysth.do") public void test(int cou ...
- delphi中如何将string类型的字符串数据转化成byte[]字节数组类型的数据
var S:String; P:PChar; B:array of Byte;begin S:='Hello'; SetLength(B,Length(S)+1); P:=PChar(S) ...
- 【hibernate】Hibernate SQL 方言(hibernate.dialect)
参考如下: RDBMS Dialect DB2 org.hibernate.dialect.DB2Dialect DB2 AS/400 org.hibernate.dialect.DB2400Dial ...
- spring batch的使用和定时器Quart的使用
Spring Batch是一个基于Spring的企业级批处理框架,它通过配合定时器Quartz来轻易实现大批量的数据读取或插入,并且全程自动化,无需人员管理. 在使用spring batch之前,得对 ...
- 席位分配问题——惯例Q值法和d'hondt法的MATLAB程序
本篇博文为追忆以前写过的算法系列第四篇 温故知新 本篇于2009年发表于百度博客,当时还没接触CSDN.所以是文学和技术博客混淆,只是这个程序博文訪问量突破2000,有不少网友评论互动.应该 ...
- mapreduce_template
Hadoop Tutorial - YDN https://developer.yahoo.com/hadoop/tutorial/module4.html import java.io.IOExce ...
- \\s+ split替换
出自: http://www.tuicool.com/articles/vy2ymm 详解 "\\s+" 正则表达式中\s匹配任何空白字符,包括空格.制表符.换页符等等, 等价于[ ...