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的更多相关文章

  1. java 又一次抛出异常 相关处理结果演示样例代码

    java 又一次抛出异常 相关处理结果演示样例代码 package org.rui.ExceptionTest; /** * 又一次抛出异常 * 在某些情况下,我们想又一次掷出刚才产生过的违例,特别是 ...

  2. java 线程 原子类相关操作演示样例 thinking in java4 文件夹21.3.4

    java 线程  原子类相关操作演示样例 package org.rui.thread.volatiles; import java.util.Timer; import java.util.Time ...

  3. linux系统编程:线程同步-相互排斥量(mutex)

    线程同步-相互排斥量(mutex) 线程同步 多个线程同一时候訪问共享数据时可能会冲突,于是须要实现线程同步. 一个线程冲突的演示样例 #include <stdio.h> #includ ...

  4. java 线程、线程池基本应用演示样例代码回想

    java 线程.线程池基本应用演示样例代码回想 package org.rui.thread; /** * 定义任务 * * @author lenovo * */ public class Lift ...

  5. Java线程演示样例 - 继承Thread类和实现Runnable接口

    进程(Process)和线程(Thread)是程序执行的两个基本单元. Java并发编程很多其它的是和线程相关. 进程 进程是一个独立的执行单元,可将其视为一个程序或应用.然而,一个程序内部同事还包括 ...

  6. Java多线程演示样例(模拟通话,sleep,join,yield,wait,notify,Semaphore)

    主线程等待子线程的多种方法 synchronized浅析 sleep 是静态方法,Thread.sleep(xx)谁调用谁睡眠. join 是合并方法.当前线程调用其它线程xx.join()则等到xx ...

  7. java 覆盖hashCode()深入探讨 代码演示样例

    java 翻盖hashCode()深入探讨 代码演示样例 package org.rui.collection2.hashcode; /** * 覆盖hashcode * 设计HashCode时最重要 ...

  8. Java 8 时间日期库的20个使用演示样例

    除了lambda表达式,stream以及几个小的改进之外,Java 8还引入了一套全新的时间日期API,在本篇教程中我们将通过几个简单的任务演示样例来学习怎样使用Java 8的这套API.Java对日 ...

  9. HBase总结(十一)hbase Java API 介绍及使用演示样例

    几个相关类与HBase数据模型之间的相应关系 java类 HBase数据模型 HBaseAdmin 数据库(DataBase) HBaseConfiguration HTable 表(Table) H ...

随机推荐

  1. ajax简单案例

    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"% ...

  2. iOS 汉字转拼音 PinYin4Objc

    PinYin4Objc 是一个效率很高的汉字转拼音类库,支持简体和繁体中文.有以下特性:1.效率高,使用数据缓存,第一次初始化以后,拼音数据存入文件缓存和内存缓存,后面转换效率大大提高:2.支持自定义 ...

  3. Understanding Objective-C Blocks

    The aim of this tutorial is to give a gentle introduction to Objective-C blocks while paying special ...

  4. 【spring boot】8.spring boot的日志框架logback使用

    在继续上一篇的Debug调试之后,把spring boot的日志框架使用情况逐步蚕食. 参考:http://tengj.top/2017/04/05/springbo 开篇之前,贴上完整applica ...

  5. python GIL

    https://www.cnblogs.com/MnCu8261/p/6357633.html 全局解释器锁,同一时间只有一个线程获得GIL,

  6. C 命令行参数

    C 命令行参数 执行程序时,可以从命令行传值给 C 程序.这些值被称为命令行参数,它们对程序很重要,特别是当您想从外部控制程序,而不是在代码内对这些值进行硬编码时,就显得尤为重要了. 命令行参数是使用 ...

  7. PhoneNumber

    项目地址:PhoneNumber 简介:一个获取号码归属地和其他信息(诈骗.骚扰等)的开源库   一个获取号码归属地和其他信息(诈骗.骚扰等)的开源库.支持本地离线(含归属地.骚扰.常用号码)和网络( ...

  8. Vue 响应式数据说明

    值得注意的是只有当实例被创建时 data 中存在的属性才是响应式的.也就是说如果你添加一个新的属性,比如: vm.b = 'hi' 那么对 b 的改动将不会触发任何视图的更新. 这里唯一的例外是使用  ...

  9. Linux是怎么启动的(整理)

    昨天笔试考了一道关于linux系统启动的过程,当时没答上来,现在整理出来(其实并不复杂). 按下电源按钮的直到欢迎页出来之后,linux总共做的事可以分为五步来完成. 1.  BIOS加电自检: 加电 ...

  10. windows平台下为Nginx反向代理(负载均衡)使用openssl增加HTTPS/SSL功能。

    1.准备好perl/openssl ActivePerl-5.12.2.1202-MSWin32-x86-293621.msi openssl-0.9.8k.tar.gz 编译 参考这个:http:/ ...