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 ...
随机推荐
- P4151 [WC2011]最大XOR和路径
P4151 [WC2011]最大XOR和路径 一道妙极了的题. 首先直接从1走到n 然后现在图上有很多环 所以可以在走到n之后走到环上一个点,再走一遍环,再原路返回.这样就会xor上环的权值. 然后只 ...
- .NET:关于数据模型、领域模型和视图模型的一些思考
背景 数据模型.领域模型和视图模型是“模型”的三种角色,一些架构用一种类型表示这三种角色,如:传统三层架构.也有一些架构用两种类型表示这三种角色,如:结合ORM的领域驱动架构.非常少见的场景是用三种类 ...
- [PLC]ST语言七:MOV_SMOV_CML_BMOV_FMOV_XCH_BCD_BIN
一:MOV/SMOV/CML/BMOV/FMOV/XCH/BCD/BIN 说明:简单的顺控指令不做其他说明. (MOV)控制要求:无 (MOV)编程梯形图: (MOV)结构化编程ST语言: (*传送指 ...
- android安卓生成密钥keystore(命令控制)
android安卓生成密钥keystore(命令控制) • 配置JDK 详细教程 https://blog.csdn.net/u012934325/article/details/73441617/ ...
- 测试模型---V模型
软件测试&软件工程 软件测试是软件工程不可缺少的一部分. 一.V模型简介 需求分析 验收测试 概要设计 系统测试 详细设计 集成测试 编码 单元测试 (1)单元测试: 又称模块测试,针对软 ...
- linux shell 完成批量压缩文件
首先得到文件列表 使用 list -1 注意是1 不是l 然后是用一个循环内包装zip代码 #!/bin/bash list=`` for var in $list do echo $var zip ...
- 教你如何编写、保存与运行 Python 程序
第一步 接下来我们将看见如何在 Python 中运行一个传统的“Hello World”程序.Python教程本章将会教你如何编写.保存与运行 Python 程序. 通过 Python 来运行的你的程 ...
- SpringCloud 学习(二) :服务注册与发现Eureka
Spring Cloud应用中可以支持多种的服务治理框架,比如Eureka.Consul.Zookeeper等,现在我们用的是consul,本文以SpringCloud Dalston.SR5版本介绍 ...
- flask中的if __name__ == "__main__"
在编写python文件时,一般会在入口文件中加入if __name__ == "__main__", 这样当这个脚本文件执行时就会执行这个语句下面的内容,而如果这个脚本文件被当作模 ...
- Datawhale MySQL 训练营 Task5
数据导入导出 导入table http://www.runoob.com/mysql/mysql-database-import.html 导出table http://www.runoob.com/ ...