multi thread for Java
I try to do a testing for HashTable Sychronized behavior today.
As an Sychronized Object, HashTable already an Sychronized at put and get function. I wanna to know more about the iterator behaviors on multi-threading.
package leetcode; import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map.Entry; public class MultiThread {
static Hashtable<Integer, Integer> sharedTable = new Hashtable<Integer, Integer>();
static final class ThreadOne implements Runnable{
public ThreadOne(){ }
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("Thread One running: add key-value pair to sharedTable");
for(int i = 0; i < 20; i ++){
sharedTable.put(i, i);
System.out.println("Put " + i + " into sharedTable");
}
}
} static final class ThreadTwo implements Runnable{
public ThreadTwo(){ }
@Override
public void run(){
System.out.println("Thread Two running: iterate the hashtable");
Iterator it = sharedTable.entrySet().iterator();
while(it.hasNext()){
Entry<Integer, Integer> entry = (Entry<Integer, Integer>) it.next();
System.out.println("entry in sharedTable:" + entry.getKey() +" with value:" + entry.getValue());
}
}
} public static void main(String[] agrs){
ThreadOne t1 = new ThreadOne();
ThreadTwo t2 = new ThreadTwo();
System.out.println("Thread start...");
new Thread(t1).start();
new Thread(t2).start();
System.out.println("Thread all started.");
}
}
I make two thread.
ThreadOne do put to hashTable.
ThreadTwo use an iterator to traversal the hashTable.
However, the output is:
Thread start...
Thread all started.
Thread Two running: iterate the hashtable
Thread One running: add key-value pair to sharedTable
Put 0 into sharedTable
Put 1 into sharedTable
Put 2 into sharedTable
Put 3 into sharedTable
Put 4 into sharedTable
Put 5 into sharedTable
Put 6 into sharedTable
Put 7 into sharedTable
Put 8 into sharedTable
Put 9 into sharedTable
Put 10 into sharedTable
Put 11 into sharedTable
Put 12 into sharedTable
Put 13 into sharedTable
Put 14 into sharedTable
Put 15 into sharedTable
Put 16 into sharedTable
Put 17 into sharedTable
Put 18 into sharedTable
Put 19 into sharedTable
Iterator is initated, however it.hasNext() return false and then exit.
This means that Iterator is broken by put function. It is not sychronized for thread.
So how to make it sychronized?
package leetcode; import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map.Entry; public class MultiThread {
static final class Shared{
private static Hashtable<Integer, Integer> sharedTable = new Hashtable<Integer, Integer>(); public Shared(){
sharedTable = new Hashtable<Integer, Integer>();
}
public synchronized static void put(Integer key, Integer val){
System.out.println("put (" + key + ":" + val + ")into sharedTable.");
sharedTable.put(key, val);
} public synchronized static Integer get(Integer key){
return sharedTable.get(key);
} public synchronized static Boolean containsKey(Integer key){
return sharedTable.containsKey(key);
} public synchronized static void traversal(){
System.out.println("traversal on the sharedTable...");
Iterator it = sharedTable.values().iterator();
while(it.hasNext()){
Integer val = (Integer)it.next();
System.out.println("sharedTable contains val: " + val);
}
System.out.println("Finish traversal.");
} }
static final class ThreadOne implements Runnable{
public ThreadOne(){ }
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("Thread One running: add key-value pair to sharedTable");
for(int i = 0; i < 20; i ++){
Shared.put(i, i);
}
}
} static final class ThreadTwo implements Runnable{
public ThreadTwo(){ }
@Override
public void run(){
System.out.println("Thread Two running: iterate the hashtable");
Shared.traversal();
}
} public static void main(String[] agrs) throws InterruptedException{
ThreadOne t1 = new ThreadOne();
ThreadTwo t2 = new ThreadTwo();
System.out.println("Thread start...");
new Thread(t1).start();
Thread.sleep(1);
new Thread(t2).start();
System.out.println("Thread all started.");
}
}
One way to solve is put sharedResources into an Bean. And for all getter / setter / traversal make them sychronized. All the customer/ producor have to call this class to use resources( this is the idea of broker, who is working between clinet and servers).
output:
Thread start...
Thread One running: add key-value pair to sharedTable
put (0:0)into sharedTable.
put (1:1)into sharedTable.
put (2:2)into sharedTable.
put (3:3)into sharedTable.
Thread all started.
put (4:4)into sharedTable.
put (5:5)into sharedTable.
put (6:6)into sharedTable.
Thread Two running: iterate the hashtable
put (7:7)into sharedTable.
traversal on the sharedTable...
sharedTable contains val: 7
sharedTable contains val: 6
sharedTable contains val: 5
sharedTable contains val: 4
sharedTable contains val: 3
sharedTable contains val: 2
sharedTable contains val: 1
sharedTable contains val: 0
Finish traversal.
put (8:8)into sharedTable.
put (9:9)into sharedTable.
put (10:10)into sharedTable.
put (11:11)into sharedTable.
put (12:12)into sharedTable.
put (13:13)into sharedTable.
put (14:14)into sharedTable.
put (15:15)into sharedTable.
put (16:16)into sharedTable.
put (17:17)into sharedTable.
put (18:18)into sharedTable.
put (19:19)into sharedTable.
Or dont sychronized the whole function, only for the part that use the resource. In this way, actually we dont need an specific class to encapture the resources:
package leetcode; import java.util.Hashtable;
import java.util.Iterator; public class MultiThread {
static final class ThreadOne implements Runnable{
public ThreadOne(){ }
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("Thread One running: add key-value pair to sharedTable");
for(int i = 0; i < 100; i ++){
synchronized(sharedTable){
System.out.println("put (" + i + ":" + i + ")into sharedTable.");
sharedTable.put(i, i);
}
}
}
} static final class ThreadTwo implements Runnable{
public ThreadTwo(){ }
@Override
public void run(){
System.out.println("Thread Two running: iterate the hashtable");
System.out.println("traversal on the sharedTable...");
synchronized(sharedTable){
Iterator it = sharedTable.values().iterator();
while(it.hasNext()){
Integer val = (Integer)it.next();
System.out.println("sharedTable contains val: " + val);
}
}
System.out.println("Finish traversal.");
}
} public static void main(String[] agrs) throws InterruptedException{
ThreadOne t1 = new ThreadOne();
ThreadTwo t2 = new ThreadTwo();
System.out.println("Thread start...");
new Thread(t1).start();
Thread.sleep(1);
new Thread(t2).start();
System.out.println("Thread all started.");
}
private static Hashtable<Integer, Integer> sharedTable = new Hashtable<Integer, Integer>();
}
multi thread for Java的更多相关文章
- Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
学习架构探险,从零开始写Java Web框架时,在学习到springAOP时遇到一个异常: "C:\Program Files\Java\jdk1.7.0_40\bin\java" ...
- Exception in thread "main" java.lang.NoSuchMethodError: org.objectweb.asm.ClassWriter.<init>(I)V
在学习CGlib动态代理时,遇到如下错误: Exception in thread "main" java.lang.NoSuchMethodError: org.objectwe ...
- GUI学习中错误Exception in thread "main" java.lang.NullPointerException
运行时出现错误:Exception in thread "main" java.lang.NullPointerException 该问题多半是由于用到的某个对象只进行了声明,而没 ...
- 执行打的maven jar包时出现“Exception in thread "main" java.lang.SecurityException: Invalid signature file digest for Manifest main attributes”
Exception in thread "main" java.lang.SecurityException: Invalid signature file digest for ...
- Exception in thread "main" java.lang.ExceptionInInitializerError
Exception in thread "main" java.lang.ExceptionInInitializerErrorCaused by: java.util.Missi ...
- 编译运行java程序出现Exception in thread "main" java.lang.UnsupportedClassVersionError: M : Unsupported major.minor version 51.0
用javac编译了一个M.java文件, 然后用java M执行,可是出现了下面这个错误. Exception in thread "main" java.lang.Unsuppo ...
- dom4j使用xpath报异常 Exception in thread "main" java.lang.NoClassDefFoundError: org/jaxen/NamespaceContext
Exception in thread "main" java.lang.NoClassDefFoundError: org/jaxen/NamespaceContext ...
- Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
场景:eclipse中编写java中用到数组 问题: 程序不报错但是运行过程中 终止,显示字样 “ Exception in thread "main" java.lang.Arr ...
- dbca:Exception in thread "main" java.lang.UnsatisfiedLinkError: get
在64位的操作系统安装oracle10g 软件安装完成后,使用dbca建库的时候报下面的错: $ dbcaUnsatisfiedLinkError exception loading native l ...
随机推荐
- P4438 [HNOI/AHOI2018]道路
辣稽题目 毁我青春 耗我钱财. 设\(f[x][i][j]\)为从1号点走到x点经过i条公路j条铁路,子树的最小代价. \(f[leaf][i][j]=(A+i)(B+j)C\) \(f[x][i][ ...
- python 小技巧之获取固定下面包含的某种类型文件的个数
遇到这样一个问题.我想要统计某个文件夹下有多少个py文件怎么办. 用python能解决吗?答案,能. 解决办法,使用glob 代码如下: import glob path_file_number=gl ...
- Spring学习(十八)----- Spring AOP+AspectJ注解实例
我们将向你展示如何将AspectJ注解集成到Spring AOP框架.在这个Spring AOP+ AspectJ 示例中,让您轻松实现拦截方法. 常见AspectJ的注解: @Before – 方法 ...
- Fiddler 抓包https配置 提示:creation of the root certificate was not successful 证书安装不成功
window7 提示:creation of the root certificate was not successful 证书安装不成功 1.cmd 命令行 找到fiddler的安装目录 如 ...
- pandas安装以及出现的问题
pandas安装以及出现的问题 1.pandas 安装 pandas是Python的第三方库,所以使用前需要安装一下,直接使用pip install pandas就会自动安装,安装成功后显示的以下的信 ...
- 旧的 .NET Core 项目重新打包出现提示版本不对问题
错误提示 当电脑更新 VS2017 版本后,如果同时有新的 .NET Core SDK 更新,打开旧的项目重新打包,可能会报这样的错误 NETSDK1061: 项目是使用 Microsoft.NETC ...
- 统计学习方法c++实现之二 k近邻法
统计学习方法c++实现之二 k近邻算法 前言 k近邻算法可以说概念上很简单,即:"给定一个训练数据集,对新的输入实例,在训练数据集中找到与这个实例最邻近的k个实例,这k个实例的多数属于某个类 ...
- if _ else if _ else,case,程序逻辑判断- java基础
//单个判端 if(){ } //双判端 if(){ }else{ } //多重判端 if(){ }else if(){ }else if(){ }else{ } package test1; // ...
- HTML(2)普通文本的修饰
段落标签 <p> 我们使用<p>...</p>标签来标记一个段落,两个段落之间会自动换行.需要注意的是,在书写HTML时,连续的空格只被看作一个空格,如果需要插入空 ...
- Django数据库 相关之select_related/prefetch_related
- 性能相关 user_list = models.UserInfo.objects.all() for row in user_list: # 只去取当前表数据 select_related,主动连 ...