多线程并发的问题解决方案

Posted 鼠标

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多线程并发的问题解决方案相关的知识,希望对你有一定的参考价值。

多线程并发的问题解决方案

package map;

import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

public class TestConCurrentMap {
static int index;
public static void main(String[] args) {
execute();
}

public static synchronized void execute(){
final Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < 10; i++) {
new Thread(new Runnable() {
public void run() {
map.put(index++, index);
while(true){
System.out.println(Thread.currentThread().getName()+":"+map);
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}).start();
}
}
}

 

----------------------------------------------------------------------------------------------------------
// @Test
public void testIsClose4WBDMultiThread(){
System.out.println("多线程测试开始。。。。。。。。");
Runnable task = new Runnable() {

@Override
public void run() {
try {
System.out.println("进入task任务");
TradingHourServiceProvider provider = TradingHourServiceProvider.get();
boolean b = provider.isClose4WBD(DateUtil.toDate("2017-09-06", DateUtil.PATTERN_DATE2));
System.out.println(b);
// Map<CacheType, String> cache = ConfigCache.get().getCache();
} catch (GenericTsException e) {
e.printStackTrace();
}
}
};
Map<Thread, String> map = new HashMap<Thread,String>();
for(int i =0;i<20;i++){
Thread t = new Thread(task);
t.currentThread().setName("线程"+i);
map.put(t, t.getName());
}

Set<Thread> threadSet = map.keySet();
for (Thread t : threadSet) {
t.start();
}

try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println("多线程测试结束。。。。。。。。");
}

@Test
public void testHashMapMultiThread(){
System.out.println("多线程测试开始。。。。。。。。");
Runnable task = new Runnable() {

@Override
public void run() {
try {
System.out.println("进入task任务");
TradingHourServiceProvider provider = TradingHourServiceProvider.get();
boolean b = provider.isClose4WBD(DateUtil.toDate("2017-09-06", DateUtil.PATTERN_DATE2));
System.out.println(b);
// Map<CacheType, String> cache = ConfigCache.get().getCache();
} catch (GenericTsException e) {
e.printStackTrace();
}
}
};
Map<Thread, String> map = new HashMap<Thread,String>();
for(int i =0;i<8;i++){
Thread t = new Thread(task);
t.currentThread().setName("线程"+i);
map.put(t, t.getName());
}

Set<Thread> threadSet = map.keySet();
for (Thread t : threadSet) {
t.start();
}

try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println("多线程测试结束。。。。。。。。");
}

以上是关于多线程并发的问题解决方案的主要内容,如果未能解决你的问题,请参考以下文章

项目中怎么控制多线程高并发访问

项目中怎么控制多线程高并发访问

怎么实现springMVC 多线程并发

多线程必看之JAVA线程并发辅助类

多线程并发的问题解决方案

c# 多线程 并发 Semaphore\AutoResetEvent都无法解决的需求~有人会吗?