码迷,mamicode.com
首页 > 编程语言 > 详细

java 线程 被互斥阻塞、检查中断示例讲解----thinking java4

时间:2014-10-06 16:05:40      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:线程   对象   thread   class   

bubuko.com,布布扣

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
*/
bubuko.com,布布扣

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
 */

bubuko.com,布布扣

bubuko.com,布布扣

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
*/


bubuko.com,布布扣

java 线程 被互斥阻塞、检查中断示例讲解----thinking java4

标签:线程   对象   thread   class   

原文地址:http://blog.csdn.net/liangrui1988/article/details/39828233

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!