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 ...
随机推荐
- org.apache.commons.io.Charsets
requiredCharsets:由Java平台支持字符集对象标准名称,构造一个sorted map. public void test() { Map<String, Charset> ...
- 使用PreloadJS加载图片资源
一. 使用createjs里的LoadQueue函数实现异步加载图片,监听加载进度 1.实例对象LoadQueue加载队列对象 var queue = new createjs.LoadQueue(f ...
- Windows Server 2008 IE 无法调整安全级别
开始”/“程序”/“管理工具”/“服务器管理器”命令,在弹出的服务器管理器窗口中,找到“安全信息”设置项,单击其中的“配置IE ESC”选项,打开如下图所示的IE增强安全配置窗口.
- 【报错】项目启动,仅仅报错 One or more listeners failed to start. Full details will be found in the appropriate container log file
今天spring4.3.13 项目,整合ActiveMQ的时候,项目启动在自动部署到tomcat下的时候,不能正常的部署,仅仅报错如下: Connected to server [-- ::,] Ar ...
- ubuntu下apache添加https支持
http是无状态,不安全的连接.而https是通过ssl加密的http连接,可靠性更强. 确保openssl安装完成,用openssl来产生和签署证书,可以自己签署,但是不安全,建议用证书机构颁发的证 ...
- 【GLSL教程】(一)图形流水线 【转】
http://blog.csdn.net/racehorse/article/details/6593719 这是一些列来自lighthouse3d的GLSL教程,非常适合入门.我将边学习边翻译该教程 ...
- 七天学会ASP.NET MVC (二)——ASP.NET MVC 数据传递 【转】
http://www.cnblogs.com/powertoolsteam/p/MVC_two.html 通过第一天的学习之后,我们相信您已经对MVC有一些基本了解. 本节所讲的内容是在上节的基础之上 ...
- VS2010 C#调用C++ DLL文件 【转】
http://www.soaspx.com/dotnet/csharp/csharp_20110406_7469.html 背景 在项目过程中,有时候你需要调用非C#编写的DLL文件,尤其在使用一些第 ...
- opencv-2.4.11编译备忘
编译完成后,想测试example中例子,但是由于没有sudo权限,不能运行pkg-config查看opencv的--cflags和--libs. 记录一下,备忘: pkg-config --libs ...
- java 几个线程池的理解
http://www.cnblogs.com/dolphin0520/p/3932921.html 这个文章写的很好