易截截图软件、单文件、免安装、纯绿色、仅160KB

Java线程同步示例

文章用实例代码展示了Java中多线程访问共享资源
时线程同步
的重要性。
分别通过在两个线程中同时访问(调用get_id*方法)经过同步处理(lock及Synchronized)的共享资源(tmp)及未经过同步处理的共享资源(tmp)来说明同步处理的的作用。
main中分两部分:
1)前半部分,non-synchronization部分用来测试没有做同步处理的代码段,运行结果应该是
After thread #1 call get_id(), id=1
After thread #2 call get_id(), id=1
2)后半部分,synchronization部分用来测试做过同步处理的代码段,运行结果应该是
After thread #1 call get_id(), id=1
After thread #2 call get_id(), id=2
参考资料:
-1-关于sleep和wait区别看一下这个: http://wurd.javaeye.com/blog/174563。
-2-关于synchronized可以看一下这篇:http://www.wangchao.net.cn/bbsdetail_148670.html,比较明了。
-3-关于Java线程同步可以看一下这个:http://lavasoft.blog.51cto.com/62575/27069,很详细。
/********************************************************************************
*FileName: Thread_sync.java
*Date: 2010/01/12
*Intention: Test thread synchronization tools in java.
*Input:
*Output:
* in non-synchronization version
* After thread #1 call get_id(), id=1
* After thread #2 call get_id(), id=1
* in synchronization version
* After thread #1 call get_id(), id=1
* After thread #2 call get_id(), id=2
*
*DevelopmentEnv: Netbeans 6.8, Jdk 1.6.
********************************************************************************/
class Counter
{
private final static Object lock = new Object();
private static int count = 0;

public int get_id()
{
int tmp = count;
++tmp;
try
{
Thread.sleep(1000);
}
catch(Exception e)
{
}
count = tmp;

return count;
}
public int get_id_sync()
{
synchronized(lock)
{
int tmp = count;
++tmp;
try
{
Thread.sleep(1000);
}
catch(Exception e)
{
}
count = tmp;
}

return count;
}
}
public class Thread_sync
{
private static int cnt = 0;
static class Rab implements Runnable
{


相关文档:

Java Web开发相关名词解释

Web开发中经常用到的一些名词,按同功能类型的进行分组:
1.标签:WebWork标签、JSTL、JSP标签
2.AOP 拦截器 过滤器 监听器 校验器
3.面向接口 面向切面 控制反转 依赖注入
4.单态模式 DAO模式 装饰模式
5.缓存:数据缓存 服务器端缓存 客户端缓存
6.ORM EJB[三种Bean]
7.JMS
8.MVC开发模式
9.W ......

JAVA实现的大整数加法

public class Test{ 
  public static String addBigNum(String str1,String str2){
     //找出两字符串的长短,方便后边引用;
     String longer = str1.length() > str2.length()? str1 : str2;
     String shorter = str1.length( ......

JAVA规范学习——String字面常量

package testPackage;
class Test {
public static void main(String[] args) {
String hello = "Hello", lo = "lo";
System.out.print((hello == "Hello") + " ");
System.out.print((Other.hello == hello) + " ");
System.out.print((other.Other.hello == hello) + " ");
System.out.print((hello == ("Hel"+"lo ......

java程序员成长全计划

=====================================
前言
在太原经历了一年的痛苦开发之后,项目已经日趋稳定,接下来的工作就是拿现有的代码到其他的省市进行实施、然后做一些本地化开发。日子相对轻松了许多,于是可以抽出时间来温习一下基础的技术知识,给自己列了一个复习提纲,这也是一个java程序员所应该掌握的知识脉络。
=== ......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号