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. OpenSSL使用3(基本原理及生成过程)(转)

    1. 基本原理 OpenSSL初接触的人恐怕最难的在于先理解各种概念 公钥/私钥/签名/验证签名/加密/解密/非对称加密 我们一般的加密是用一个密码加密文件,然后解密也用同样的密码.这很好理解,这个是 ...

  2. 课程设计之"网络考试系统"(php、Extjs)

    1.TestSystem大概结构框图 2.数据库设计(11张表) 数据库名称:db_testsystem 数据库表: tb_admin 记录题库管理员帐户信息 代码 tb_allcontent 记录随 ...

  3. linux命令lsattr、chattr、man

    1.man命令,可以查看手册 配置位置/etc/man.conf MANPATH决定手册查询位置 MANSECT决定man查询的顺序 man的查询 linux man的常用用法: man sectio ...

  4. Web攻防之XSS,CSRF,SQL注入(转)

    摘要:对Web服务器的攻击也可以说是形形色色.种类繁多,常见的有挂马.SQL注入.缓冲区溢出.嗅探.利用IIS等针对Webserver漏洞进行攻击.本文结合WEB TOP10漏洞中常见的SQL注入,跨 ...

  5. 【GLSL教程】(六)逐顶点的光照 【转】

    引言 在OpenGL中有三种类型的光:方向光(directional).点光(point).聚光(spotlight).本教程将从方向光讲起,首先我们将使用GLSL来模仿OpenGL中的光. 我们将向 ...

  6. http://preshing.com/

    http://preshing.com/ http://mechanical-sympathy.blogspot.com/

  7. GIS可视化

    作为一名GIS专业的学生,一晃也毕业三年了,在supermap也呆了三年多了,做的最多的就是浏览器端的GIS展示,最近也想分享一下我们团队在浏览器端GIS可视化的一些成果,算是做个宣传吧!有用的着的可 ...

  8. Hadoop部署启动异常问题排查

    hadoop的日志目录(/home/hadoop/app/hadoop-2.6.4/logs) 1.hadoop启动不正常用浏览器访问namenode的50070端口,不正常,需要诊断问题出在哪里: ...

  9. 移动端弹窗 layer.js 使用

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  10. vue组件class绑定

    当在一个自定义组件上使用 class 属性时,这些类将被添加到该组件的根元素上面.这个元素上已经存在的类不会被覆盖. 例如,如果你声明了这个组件: Vue.component('my-componen ...