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( ......
Java Learning Path (一)、工具篇
一、 JDK (Java Development Kit)
JDK是整个Java的核心,包括了Java运行环境(Java Runtime Envirnment),一堆Java工具和Java基础的类库(rt.jar)。不论什么Java应用服务器实质都是内置了某个版本的JDK。因此掌握JDK是学好Java的第一步。最主流的JDK是Sun公司发布的JDK,除了Sun之外, ......
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 ......
一、使浏览器不缓存页面的过滤器
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 用于的使 Browser 不 ......
import java.util.Date;
class Dog{
private String name;
private Date birthday;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getBirthday() {
return b ......