java线程共享受限资源 解决资源竞争  具体介绍请參阅:thinking in java4 21.3

thinking in java 4免费下载:http://download.csdn.net/detail/liangrui1988/7580155

package org.rui.thread.res;
/**
* 不对的訪问 资源
* @author lenovo
*
*/
public abstract class IntGenerator { private volatile boolean canceled=false;//取消的
public abstract int next();
// 同意这样的被取消
public void cancel(){canceled =true;}
public boolean isCanceled(){return canceled;} }
package org.rui.thread.res;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* 不论什么IntGenerator都能够用以下的EvenCherker类来測试
* @author lenovo
*
*/
public class EvenChecker implements Runnable { private IntGenerator generator;
private final int id; public EvenChecker(IntGenerator g,int ident)
{
this.generator=g;
this.id=ident;
} @Override
public void run() {
while(!generator.isCanceled())
{
int val=generator.next();
if(val%2!=0)
{
System.out.println(val+" not even!");
generator.cancel();//cancels all evencheckers
}
} } ///test any type of intgenerator
public static void test(IntGenerator gp,int count)
{
System.out.println("press control-c to exit");
ExecutorService ex=Executors.newCachedThreadPool();
for(int i=0;i<count;i++)
{
ex.execute(new EvenChecker(gp,i));
}
ex.shutdown(); /*for(int i=0;i<count;i++)
{
Thread t=new Thread(new EvenChecker(gp,i));
t.start();
}*/ } ///
public static void test(IntGenerator gp)
{
test(gp,10);
} }
package org.rui.thread.res;
/**
* 这个程序终于会失败,由于evenChecker任务在evenGenerator处于 不恰当的 状态时
* 仍可以訪问当中信息
* 假设你希望更快地发现失败。可以尝试着将yield() 的调用放置到第一个和第二个递增操作之间。
* 这仅仅是并发程序的部分部题
* @author lenovo
*
*/
public class EvenGenerator extends IntGenerator { private int currentEvenValue=0; @Override
public int next() {
++currentEvenValue;//危急项目》的出版物! danger point here
++currentEvenValue;
return currentEvenValue; } public static void main(String[] args) {
EvenChecker.test(new EvenGenerator());
} }
/**
* output:
press control-c to exit
13103419 not even!
*/
package org.rui.thread.res;
/**
* 同步控制 EvenGenerator
* @author lenovo
*
*/
public class SynchronizedEvenGenerator extends IntGenerator { private int currentEvenValue=0;
@Override
public synchronized int next() {
++currentEvenValue;
Thread.yield();//导致失败的更快 暂停当前正在运行的线程对象。并运行其它线程。 ++currentEvenValue;
return currentEvenValue;
} public static void main(String[] args) {
EvenChecker.test(new SynchronizedEvenGenerator());
}
}
/**
output:
press control-c to exit
*/
package org.rui.thread.res;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock; /**
* 使用显示的Lock对象
* @author lenovo
*
*/
public class MutexEvenGenerator extends IntGenerator {
private int currentEvenValue=0; Lock lock=new ReentrantLock();
@Override
public int next() {
lock.lock();
try {
++currentEvenValue;
Thread.yield();//导致失败的更快 暂停当前正在运行的线程对象,并运行其它线程。 ++currentEvenValue;
return currentEvenValue;
} finally
{
lock.unlock();
}
}
//////////////////////////////
public static void main(String[] args)
{
EvenChecker.test(new MutexEvenGenerator()); } } /**
output:
press control-c to exit
*/
package org.rui.thread.res;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock; /**
* synchronizedkeyword不能尝试着获取锁且终于获取锁会失败
* 或都尝试获取一段时间 。然后放弃它。要实现这些。你必须使用concurrent类库:
*
*
* ReentrantLock同意你尝试着获取但终于末获取锁,这样假设其它人已经获取了这个锁,
* 那么你就能够决定离开去运行其它一些事件。而不是等待直至这个锁被释放,就像在untimed()方法中所示。
* 在timed中 做出尝试去获取锁。该尝试能够在2秒之后失败
* @author lenovo
*
*/
public class AttemptLocking {
//可重入的相互排斥锁
private ReentrantLock lock=new ReentrantLock();
public void untimed()//不计时的
{
// 仅在调用时锁未被还有一个线程保持的情况下。才获取该锁。 boolean captured=lock.tryLock();
try
{
System.out.println("tryLock(): "+captured);
} finally
{
if(captured)
lock.unlock();
}
} /////////////
public void timed()//计时
{
boolean captured=false;
try {
//假设锁在给定等待时间内没有被还有一个线程保持,且当前线程未被中断,则获取该锁。
captured=lock.tryLock(2,TimeUnit.SECONDS);
} catch(InterruptedException e)
{
throw new RuntimeException(e);
} try
{
System.out.println("tryLock(2,TimeUnit.SECONDS) : "+captured);
} finally
{
if(captured)
lock.unlock();
}
}
///////////////main
public static void main(String[] args) throws InterruptedException {
final AttemptLocking al=new AttemptLocking();
al.untimed();//true -- lock is available 锁可用
al.timed();//true -- lock is available
//如今创建一个单独的任务获取锁 使以下的线程调用产生竞争
new Thread()
{
{setDaemon(true);}
@Override
public void run() {
al.lock.lock();
System.out.println("acquired");
}
}.start();
Thread.sleep(1000);
// 暂停当前正在运行的线程对象,并运行其它线程。 //Thread.yield();//give the 2nd task a chance 给第二个任务一个机会
al.untimed();//false--lock grabbed by task 锁了的任务
al.timed();//false--lock grabbed by task
} }
/**
* output:
tryLock(): true
tryLock(2,TimeUnit.SECONDS) : true
acquired
tryLock(): false
tryLock(2,TimeUnit.SECONDS) : false
*/

java线程共享受限资源 解决资源竞争 thinking in java4 21.3的更多相关文章

  1. paip.java 线程无限wait的解决

    paip.java  线程无限wait的解决 jprofl>threads>thread dump> 查看棉线程执行的code stack... 估计是.比如.BlockingQue ...

  2. java线程安全问题原因及解决办法

    1.为什么会出现线程安全问题 计算机系统资源分配的单位为进程,同一个进程中允许多个线程并发执行,并且多个线程会共享进程范围内的资源:例如内存地址.当多个线程并发访问同一个内存地址并且内存地址保存的值是 ...

  3. java线程初写,陆续更新中。。

    (1)什么是线程?线程,是程序执行流的最小单元.线程是进程中的一个实体,是被系统独立调度和分派的基本单位,线程自己不拥有系统资源,只拥有一点儿在运行中必不可少的资源,但它可与同属一个进程的其它线程共享 ...

  4. JAVA线程基础概念及使用

    一.线程和进程的区别 在操作系统中所有运行的任务通常对应一个进程,进程是系统进行资源分配和调度的一个独立单位.线程是进程的组成部分,一个进程最少包含一个线程.并发和并行的区别是,并发指的在同一时刻内, ...

  5. Java线程池的那些事

    熟悉java多线程的朋友一定十分了解java的线程池,jdk中的核心实现类为java.util.concurrent.ThreadPoolExecutor.大家可能了解到它的原理,甚至看过它的源码:但 ...

  6. java线程不安全类与写法

    线程不安全类 1.为什么java里要同时提供stringbuilder和stringbuffer两种字符串拼接类 2.simpledateformate是线程不安全的类,如果把它作为全局变量会有线程安 ...

  7. python中线程共享资源问题的解决

    线程跟进程有些相似,有时被称作轻量级的进程,但不同的是,所有的线程运行在同一个进程中,共享相同的运行坏境. 进程和线程都是实现多任务的一种方式,例如:在同一台计算机上能同时运行多个QQ(进程),一个Q ...

  8. 【Linux 线程】同一个进程中的线程共享哪些资源

    进程是具有一定独立功能的程序关于某个数据集合上的一次运行活动,进程是系统进行资源分配和调度的一个独立单位. 线程是进程的一个实体,是CPU调度和分派的基本单位,它是比进程更小的能独立运行的基本单位.线 ...

  9. Java线程基础知识(状态、共享与协作)

    1.基础概念 CPU核心数和线程数的关系 核心数:线程数=1:1 ;使用了超线程技术后---> 1:2 CPU时间片轮转机制 又称RR调度,会导致上下文切换 什么是进程和线程 进程:程序运行资源 ...

随机推荐

  1. ES6特性:(阮一峰老师)学习总结

    ES6(阮一峰)学习总结   1.块级作用域的引入 在ES6之前,js只有全局作用域和函数作用域,ES6中let关键字为其引入了块级作用域. { var a = 5; let b = 6; } con ...

  2. 常用js方法封装

    常用js方法封装 var myJs = { /* * 格式化日期 * @param dt 日期对象 * @returns {string} 返回值是格式化的字符串日期 */ getDates: fun ...

  3. Vue轮播图插件---Vue-Awesome-Swiper

    轮播图插件 Vue-Awesome-Swiper 地址:https://github.com/surmon-china/vue-awesome-swiper 安装:npm install vue-aw ...

  4. Git学习总结(9)——如何构建你自己的 Git 服务器

    现在我们将开始学习如何构建一个Git服务器,如何在具体的事件中写一个针对特定的触发操作的自定义Git(例如通告),如何发布你的代码到一个网站. 目前为止,用户对Git的焦点主要在Git的使用上.这篇文 ...

  5. Java相关知识(一)

    1. 作用域public.protected.private以及不写时的差别? public 表示公有.声明的为公共成员变量和函数成员.在整个类内类外都可使用,对全部用户开放,能够直接进行调用 pri ...

  6. Appium AndroidKeyCode

    driver.sendKeyEvent(AndroidKeyCode.BACK); driver.sendKeyEvent(AndroidKeyCode.BACKSPACE); driver.send ...

  7. MySQL循环语句之while循环测试

    转自:http://www.nuoweb.com/database/7614.html MySQL有循环语句操作,while 循环.loop循环和repeat循环,目前我只测试了 while 循环,下 ...

  8. [TJOI2017] DNA 解题报告 (hash+二分)

    题目链接:https://www.luogu.org/problemnew/show/P3763 题目大意: 给定原串S0,询问S0有多少个子串和给定串S相差不到3个字母 题解: 我们枚举S0的子串, ...

  9. String转换成int型

    private boolean judge(String str){ int year = 0; try{ year = Integer.valueOf(str).intValue(); }catch ...

  10. BZOJ 4260 trie树

    思路: 搞一个前缀异或和 一次从左往右 另一次从右往左 异或最大值 用字典树搞一搞 //By SiriusRen #include <cstdio> #include <cstrin ...