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
{
相关文档:
public class Test{
public static String addBigNum(String str1,String str2){
//找出两字符串的长短,方便后边引用;
String longer = str1.length() > str2.length()? str1 : str2;
String shorter = str1.length( ......
来源:http://bbs.hackline.net/thread-3620-1-1.html
隐藏具体实现是Java语言的主要特点之一。正是因为这个原因,所以Java语言的移植性就特别好。如有个程序员编写了一个实现随机数的程序库,那么其他
程序开发人员只需要知道这个程序库需要传入那些参数,就可以使用这个类。现在无论是网上还是平时的工作中,有很多现成 ......
import java.util.regex.*;
public final class RegExpValidator
{
/**
* 验证邮箱
* @param 待验证的字符串
* @return 如果是符合的字符串,返回 <b>true </b>,否则为 <b>false </b>
*/
public static boolean isEmail(String str)
{ ......
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程序员所应该掌握的知识脉络。
=== ......