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
{
相关文档:
// 注册应用程序全局键盘事件, 所有的键盘事件都会被此事件监听器处理.
Toolkit tk = Toolkit.getDefaultToolkit();
tk.addAWTEventListener(new MyAWTEventListener(), AWTEvent.KEY_EVENT_MASK);
class MyAWTEventListener implements AWTEventListener {
private boolean controlPressed = fal ......
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 ......
1.首先写一个权限过滤filter类,实现Filter接口
/*首先写一个权限过滤filter*/
import javax.servlet.Filter;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.FilterChain;
import ......
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 ......