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. luogu P1579 哥德巴赫猜想(升级版)

    题目描述 一个等差数列是一个能表示成a, a+b, a+2b,..., a+nb (n=0,1,2,3,...)的数列. 在这个问题中a是一个非负的整数,b是正整数.写一个程序来找出在双平方数集合(双 ...

  2. SPOJ 20713 DIVCNT2 - Counting Divisors (square)

    DIVCNT2 - Counting Divisors (square) #sub-linear #dirichlet-generating-function Let \sigma_0(n)σ​0​​ ...

  3. [java基础] 002 - 位运算符的详解和妙用

    一:位运算符详解 位运算符主要用来对操作数二进制的位进行运算.按位运算表示按每个二进制位(bit)进行计算,其操作数和运算结果都是整型值. Java 语言中的位运算符分为位逻辑运算符和位移运算符两类, ...

  4. HTML DOM介绍

    HTML DOM定义了一系列的对象,以及访问和处理HTML的方法.通过DOM可以浏览所有的HTML元素,不但可以修改或者删除元素的文本和属性,而且可以创建新的元素. 一.首先对一个元素进行操作前,要得 ...

  5. [Cocoa]深入浅出Cocoa多线程编程之 block 与 dispatch quene

    深入浅出 Cocoa 多线程编程之 block 与 dispatch quene 罗朝辉(http://www.cppblog.com/kesalin CC 许可,转载请注明出处 block 是 Ap ...

  6. andriod 支付宝类似界面图片加文字

    <?xml version="1.0" encoding="utf-8"?> <GridView xmlns:android="ht ...

  7. Linux学习之十七-配置Linux简单的脚本文件自启动

    配置Linux简单的脚本文件自启动 在Linux中使用shell脚本解决一些问题会比单独执行多条命令要有效率,脚本文件规定命名以.sh结尾,最基本的规则就是其内容是命令,想要脚本文件开机自启动,就需要 ...

  8. Bag标签之校验

    校验输入的内容是不是正确(校验整数.小数.字母.汉字或日文.username.XML节点名.日期.邮件及自己定义) 使用方法: <Bagid=书包名 act=verify> <wen ...

  9. hdu 5444 Elven Postman(长春网路赛——平衡二叉树遍历)

    题目链接:pid=5444http://">http://acm.hdu.edu.cn/showproblem.php?pid=5444 Elven Postman Time Limi ...

  10. Action window Flags

    Action window 主要字段使用 含义     target 值 作用 current 当前窗口 new 新窗口 inline 内联编辑 fullscreen 全屏 main 当前窗口的主动作 ...