http://www.jbxue.com/article/5649.html 打开一个页面<?php phpinfo(); ?> 然后在游览器下运行:页面提示 No input file specified. FastCGI模式下访问php文件时,出现No input file specified.错误 查看access.log 发现是 404 打开一个页面<?php phpinfo(); ?> 然后在游览器下运行:页面提示 No input file specified. FastCGI模式下访问php文件时,出现No input file specified.错误 查看access.log 发现是 404 原因分析: 1、任何对.php文件的请求,都简单地交给php-cgi去处理,但没有验证该php文件是否存在。PHP文件不存在,没办法返回普通的404错误,它返回 一个404,并带上一句”No input file specified” 2、还可能跟 路径或者 权限有关系,或者SCRIPT_FILENAME 变量没有被正确的设置(这在nginx是最常见的原因) 1)如果html也出现404错误,那么就是document root 设置的有问题 2)检查脚本文件的权限, 可能PHP或者web server不能读取它 3)SCRIPT_FILENAME设置错误 网上的解决方法: 步骤一:修改nginx主配置文件nginx.conf 默认安装的nginx配置文件中定义fastcgi处是:fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name; 可以将它改成: fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; 必须保证 $document_root 在配置文件中,在astcgi_param SCRIPT_FILENAME前面被用到过一次, 后面有解释为什么。 步骤二:修改PHP的住配置文件php.ini 修改/etc/php5/cgi/php.ini中cgi.fix_pathinfo=1 这样也可让php-cgi正常使用SCRIPT_FILENAME这个变量 有人说,这样改也行 fastcgi_param SCRIPT_NAME /home/gavin/nginx/$fastcgi_script_name; 让我们看看PHP对这两个变量是怎么解释的吧 SCRIPT_NAME SCRIPT_FILENAME 据说,必须指定正确的SCRIPT_FILENAME, PHP-CGI会忽略SCRIPT_NAME(即使它的值设置的是正确的) 或者指定特殊的php.ini, 设置doc_root, discard path, fix pathinfo等等 script_filename 只是被用做一种快捷方式。 如果fix_pathinfo设置打开,init函数将它用来决定真实的路径 因为配置文件会改变 nginx的变量$fastcgi_script_name fastcgi_param SCRIPT_NAME /home/gavin/nginx/$fastcgi_script_name; fastcgi_param […]
View DetailsNginx Nginx有官方native build的32bit版本, 也有cygwin build的64bit版本, 出于稳定性的考虑, 还是选了官方的32bit. 解压, 本例中使用的路径是 C:\Servers\nginx-1.9.12 , 创建两个bat, 用于启动和关闭nginx: start_nginx.bat
|
1 2 3 4 |
@echo off set NGINX_HOME=C:\Servers\nginx-1.9.12 start /D %NGINX_HOME%\ %NGINX_HOME%\nginx.exe pause |
stop_nginx.bat
|
1 2 3 4 5 |
@echo off set NGINX_HOME=C:\Servers\nginx-1.9.12 cd %NGINX_HOME% nginx.exe -s quit pause |
PHP 选的版本是 7.0.4 64位 NTS(非线程安全) VC14, 本例中解压至目录 C:\Servers\php-7.0.4-nts-Win32-VC14-x64 , 使用php.ini-development 创建 php.ini, 修改以下几处, (参考 http://man.chinaunix.net/develop/php/php_manual_zh/html/ini.core.html )
|
1 2 3 4 5 6 7 8 9 10 11 |
date.timezone = Asia/Shanghai enable_dl = On #允许用户在运行时加载PHP扩展,即在脚本运行期间加载 cgi.force_redirect = 0 # 启用时, 防止任何人通过如 http://my.host/cgi-bin/php/secretdir/script.php 这样的 URL 直接调用 PHP。PHP 在此模式下只会解析已经通过了 web 服务器的重定向规则的 URL. 在大多数 web 服务器中以 CGI 方式运行 PHP 时很有必要用 cgi.force_redirect 提供安全。PHP 默认其为 On。可以将其关闭,但风险自担。注: Windows 用户:可以安全地在 IIS 之下将其关闭,事实上必须这么做。要在 OmniHTTPD 或 Xitami 之下使用也必须将其关闭。 cgi.fix_pathinfo=1 #1:PHP CGI 以 / 为分隔符号从后向前依次检查请求的路径, 对 CGI 提供了真正的 PATH_INFO/PATH_TRANSLATED 支持。以前 PHP 的行为是将 PATH_TRANSLATED 设为 SCRIPT_FILENAME,而不管 PATH_INFO 是什么。有关 PATH_INFO 的更多信息见 cgi 规格。将此值设为 1 将使 PHP CGI 修正其路径以遵守规格。设为 0 将使 PHP 的行为和从前一样。默认为零。用户应该修正其脚本使用 SCRIPT_FILENAME 而不是 PATH_TRANSLATED。 fastcgi.impersonate = 1 #IIS(在基于 WINNT 的操作系统上)中的 FastCGI 支持模仿客户端安全令牌的能力。这使得 IIS 能够定义运行时所基于的请求的安全上下文。Apache 中的 mod_fastcgi 不支持此特性(03/17/2002)。如果在 IIS 中运行则设为 1。默认为 0。 cgi.rfc2616_headers = 1 #指定 PHP 在发送 HTTP 响应代码时使用何种报头。如果设定为 0,PHP 发送一个 Status: 报头,Apache 和其它 web server 都支持。如果此选项设定为 1,PHP 将发送 RFC 2616 兼容的报头。除非你知道自己在做什么,否则保留其值为 0。 |
添加扩展, 修改以下几处
|
1 2 3 |
extension_dir = "./ext" # 指定win7下的扩展目录 # 并取消用到的扩展前面的注释 |
启动的命令是
|
1 |
C:\>Servers\php-7.0.4-nts-Win32-VC14-x64\php-cgi.exe -b 127.0.0.1:9000 |
如果需要后台启动PHP CGI, 使用vbs, 创建 startup.vbs
|
1 |
createobject("wscript.shell").run "c:\Servers\php-7.0.4-nts-Win32-VC14-x64\php-cgi.exe -b 127.0.0.1:9000",0,false |
停止PHP CGI, 创建shutdown.bat
|
1 2 3 |
@echo off taskkill /fi "imagename eq php-cgi.exe" pause |
Nginx 启用 PHP 修改nginx.conf
|
1 2 3 4 5 6 7 |
location ~ \.php$ { root html; fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } |
重启nginx 注: PHP5.6及以下, 需要将mysql 的 libmysql.dll 拷贝至 C:\Windows\SysWOW64 PHP7貌似已经取消了支持,编译都没有了--with-mysql参数,只支持--with-mysqli和--with-pdo-mysql, 故libmysql.dll已经不需要 如果提示api-ms-win-crt-runtime-l1-1-0.dll丢失, 请安装 visual c++ redistributable 2015, 从微软官网上可以下载. 安装对系统的要求必须在win7 sp1以上, 如果win7还未升级的, 安装会失败. from:https://www.cnblogs.com/milton/p/5244387.html
View DetailsXMPP是一种基于标准通用标记语言的子集XML的协议,它继承了在XML环境中灵活的发展性。因此,基于XMPP的应用具有超强的可扩展性。经过扩展以后的XMPP可以通过发送扩展的信息来处理用户的需求,以及在XMPP的顶端建立如内容发布系统和基于地址的服务等应用程序。而且,XMPP包含了针对服务器端的软件协议,使之能与另一个进行通话,这使得开发者更容易建立客户应用程序或给一个配好系统添加功能。
View Details(一):三级分销简介 三级分销,指的是品牌商可以发展三级分销商[1] ,每一级分销商均可以往下再发展两级分销商。 一:谁卖出谁拿销售佣金,无论分销商等级产品销售佣金比例一致。分销商可以无限裂变,分销商销售佣金可设置每个级别获取不同。 二:每一个分销商的下级卖出商品,上级分销商可以拿到推广佣金。推广佣金最多三级。 三:分销等级是三级,由于销售产生关系的最多只有三级。每个人都可能成为推广中的一级分销商,拿一级推广佣金。 (二):免费的三级分销系统 目前大部分平台的三级分销都收费,有部分的平台采取免费的形式。 企业可以使用三级分销制系统,让用户就可以加入企业,成为企业的分销商,企业给分销商的返利由企业自主决定。建立外围渠道销售系统,零营销费用或低营销费用实现主动营销、口碑营销,让大众既来消费又是企业的业务人员,又不用支付底薪,降低营销成本。 (三):三级分销的机制 目前的三级分销实行的是末尾三级返佣机制,即能带来购买行为的分销为一级分销商,是直接产生利益的分销,我们记做分销商F。F的上一级分销E为二级分销商,同理,D为三级分销商。商家发展了N多分销,客户小明从分销商F那里购买了商品,那么F获得一级佣金,E二级佣金,D三级佣金,D前面的分销商C,B,A就与此没有关系,也无法获得佣金。 (四):三级分销佣金的分配 通俗的来讲,末尾三级分佣,一级分销商获得佣金最多,因为是能直接为商家带来订单的分销商,发展一级分销商的二级,三级分销商会获得二级、三级佣金。 假设一个商品,价格100,成本60元。商家通过三级分销平台卖出这个商品,商家利润40元,把20元作为推广佣金给他的分销商,其中设定一级佣金为20元的百分之50%,二级佣金设定为20元的百分之30%、三级佣金设定为20元的百分之20%,那么交易一次一级分销就会获得10元佣金,二级获得6元佣金、三级会获得4元佣金。客户有多次交易,有多个客户完成了交易,商家的三个分销商每次都会获得返佣。 (五):三级分销的优势 近几年来,随着网络的普及,越来越多的品牌商,也在纷纷借助于微分销系统的帮助,让商品的销路更广泛。利用三级分销能够树立品牌产品的良好形象,增强产品的信息的传递,让商品有更多机会出现在人们的视野里面,就会给商家带来意想不到的惊喜,从而商品就能够在消费者的心目中树立良好的形象,商品只要是能够让消费者认可,就能够促进商品的销售,企业在进行产品宣传的时候,都是通过微信朋友圈进行商品的宣传,利用这种产品宣传的方式,更容易让人们接受。 from:https://baike.baidu.com/item/%E4%B8%89%E7%BA%A7%E5%88%86%E9%94%80/18870664?fr=aladdin
View Details1、ArrarList 转换为 string[] ArrayList list = new ArrayList(); list.Add("aaa"); list.Add("bbb"); //转换成数组 string[] arrString = (string[])list.ToArray(typeof( string)); 2、string[] 转换为 ArrarList ArrayList list = new ArrayList(new string[] { "aaa", "bbb" }); 3、ArrayList 转换为 string ArrayList list = new ArrayList(); list.Add("aaa"); list.Add("bbb"); //转换成数组 string str= string.Join(",", (string[])list.ToArray(typeof( string))); 4、string 转换为 ArrayList string str="1,2,3,4,5"; ArrayList b = new ArrayList( str.Split(',') ); from:https://www.cnblogs.com/stone_w/archive/2012/03/21/2409357.html
View Details背景 入行也13年有余了,找我做些小网站的朋友也挺多的;上传图片肯定是必备的功能,随着网速的提升,想上传些视频、音频的也挺多的。一直以来的做法也就是直接做个上传功能,最多做个图片管理的功能;有些在线编辑器也带有这些功能,如CKEditor(原FCKEditor)、Kindeditor等。但这种图片或文件管理也以用为主,对于文章已经删除,图片还留在服务器情况也得选择不去理会。这段终于闲了些,于是把多媒体文件的自动删除功能做上,也算圆满。 概述 大概思路就是记录每一个上传的文件,然后在任何引用些文件的地方也记录一下,当删除文章时就更新一下引用总数,如果发现引用数为0时则删除媒体文件。 实现思路 首先建议两个表,分别用来记录媒体文件和引用关系。 在添加文章时,记录上传的文件和引用关系。 在修改文章时,先查询出现有的引用关系备用;然后用正则从将要更新的文章信息、其他字段取出所有媒体文件(包括新增的和原有的),最后遍历一下媒体文件列表,把新的媒体文件入库并增加引用关系;再遍历刚才已经查询出的现有引用关系列表,检查出哪些媒体文件不再引用,先删除引用关系,如果发现某个媒体文件的引用次数是0,则删除媒体文件。 在删除文章时,删除文章所有引用媒体文件的记录,检查每一个媒体文件的引用次数,引用次数为0时则删除媒体文件。 以上就是我对上传到服务器的媒体文件自管理的实现,希望对各位有所启发,不足之处也请补充。
View Details有关wordpress IP验证不当漏洞的通知,阿里云每天一封邮件加一条短信。虽然关系不大,但还是看着心烦。同时升级专业版不是小博客能够承受的,所以只能自己动手。 漏洞描述 wordpress /wp-includes/http.php文件中的wp_http_validate_url函数对输入IP验证不当,导致黑客可构造类似于012.10.10.10这样的畸形IP绕过验证,进行SSRF。【注意:该补丁为云盾自研代码修复方案,云盾会根据您当前代码是否符合云盾自研的修复模式进行检测,如果您自行采取了底层/框架统一修复、或者使用了其他的修复方案,可能会导致您虽然已经修复了改漏洞,云盾依然报告存在漏洞,遇到该情况可选择忽略该漏洞提示】 漏洞修复 找到wp-includes/http.php这个文件,在文件的465行附近找到:
|
1 |
$same_host = strtolower( $parsed_home['host'] ) === strtolower( $parsed_url['host'] ); |
把改行修改为成以下代码,或者注销该行添加。
|
1 2 3 4 5 |
if (isset($parsed_home['host'])) { $same_host = (strtolower($parsed_home['host']) === strtolower($parsed_url['host']) || 'localhost' === strtolower($parsed_url['host'])); } else { $same_host = false; }; |
还是这个文件,在 478行左右找以下代码
|
1 |
if ( 127 === $parts[0] || 10 === $parts[0] |
替换成
|
1 |
if ( 127 === $parts[0] || 10 === $parts[0] || 0 === $parts[0] |
如果在修改的时候发现478该行代码已经是修改过的代码,请忽略。 漏洞验证 登录阿里云帐号,在服务器安全页面点击验证。 参考连接: https://my.oschina.net/u/1433006/blog/752189 from:http://www.sijitao.net/2508.html
View Details目标:为提高数据库表更新(update)效率,使用多线程更新。其实这里也可以考虑另一种方法批量更新,不过如果更新失败了,同一事务(transaction)中的其他更新语句就会回滚,比较麻烦,所在还是简单点用多线程去处理。 困难点:开始是想把需要更新的数据等分到线程中去处理,不过搞了一段时间都没成功,主要是没有什么办法把动态参数从线程外传进线程内。后来换了个思路,每个线程去拿一条数据去更新,拿数据时同步处理。这样之后就可以了。 例子(部分外部类没有写上去,所以只能参考,要运行需要改改):
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 |
import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicInteger; import javax.annotation.Resource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; public class BaiduBaikeJob { static final Logger logger = LoggerFactory .getLogger(BaiduBaikeJob.class); @Autowired private MongoLockService mongoLockService; @Autowired private WeiboPersonService weiboPersonService; @Resource(name = "globalProperties") private PropertyPlaceholderConfigurer config; final int THREAD_COUNT = 10; AtomicInteger updCounter = new AtomicInteger(0); AtomicInteger next = new AtomicInteger(0); private CountDownLatch threadCompletedCounter = new CountDownLatch(THREAD_COUNT); /** * 每隔 1小时,获得百度百科里的人物信息 */ public void baiduBaikeRun() { if ("true".equalsIgnoreCase((String) config.getProperty("runBaiduBaikeJob", "false")) && mongoLockService.getLock(MongoLockService.LOCK_BAIDU_BAIKE)) { List<WeiboPerson> unBaikeFills = null; try { unBaikeFills = weiboPersonService.findUnBaikeFills(2000); if (unBaikeFills != null && !unBaikeFills.isEmpty()) { List<WeiboPerson> weiboPersonList = new ArrayList<WeiboPerson>(); for (final WeiboPerson person : unBaikeFills) { // 获取百度百科信息 WeiboPerson weiboPerson = BaiduBaikeUtils.getBaiduBaikeInfo(person.getName()); weiboPerson.setId(person.getId()); weiboPerson.setName(person.getName()); weiboPerson.setTenantId(person.getTenantId()); weiboPerson.setGroupId(person.getGroupId()); // 更新状态 if (!StringUtils.isEmptyString(weiboPerson.getDescription())) { weiboPerson.setFlagBaike(WeiboPerson.BAIKE_SUCCESS); } else { weiboPerson.setFlagBaike(WeiboPerson.BAIKE_FAIL); } weiboPerson.setLastUpdDate(new Date()); weiboPersonList.add(weiboPerson); } // 首次更新或过期更新 baiduBaikeRunInMultiThreads(weiboPersonList); } } catch (Exception e) { logger.error("update baidu baike error," + e.getClass().getName() + ": " + e.getMessage()); } finally { try { mongoLockService.releaseLock(MongoLockService.LOCK_BAIDU_BAIKE); } catch (Exception e) { logger.error("release lock error ", e); } } } } /** * 多线程处理:更新table */ private void baiduBaikeRunInMultiThreads(final List<WeiboPerson> weiboPersonList) { ExecutorService executor = Executors.newFixedThreadPool(THREAD_COUNT); for (int i = 0; i < THREAD_COUNT; i++) { executor.submit(new Runnable() { public void run() { WeiboPerson weiboPerson = getNext(weiboPersonList); while (null != weiboPerson) { try { // 首次更新或过期更新 weiboPersonService.update(weiboPerson); } catch (Exception e) { logger.error("table weiboPerson update error ", e); } updCounter.incrementAndGet(); // System.out.println("Thread:" + Thread.currentThread().getName() + ", counter:" + updCounter + ", name:" + weiboPerson.getName()); weiboPerson = getNext(weiboPersonList); } threadCompletedCounter.countDown(); } }); } closeThreadPool(executor); } /** * 同步处理:获取需要更新的一条微博人物 */ private synchronized WeiboPerson getNext(List<WeiboPerson> weiboPersonList){ if(next.intValue()>=weiboPersonList.size()) return null; next.incrementAndGet(); return weiboPersonList.get(next.intValue()-1); } /** * 关闭线程池 */ private void closeThreadPool(final ExecutorService executor) { try { threadCompletedCounter.await(); executor.shutdown(); } catch (InterruptedException e) { e.printStackTrace(); } } public static void main(String[] args) { // mock List<WeiboPerson> weiboPersonList = new ArrayList<WeiboPerson>(); int i = 1; while (i <= 10) { WeiboPerson weiboPerson = new WeiboPerson(); weiboPerson.setName("a" + i); weiboPersonList.add(weiboPerson); i++; } // test multi-thread BaiduBaikeJob baiduBaikeJob = new BaiduBaikeJob(); baiduBaikeJob.baiduBaikeRunInMultiThreads(weiboPersonList); } } |
from:http://blog.csdn.net/textboy/article/details/44680289
View Details1.项目背景 这里简单介绍一下项目需求背景,之前公司的项目基于EF++Repository+UnitOfWork的框架设计的,其中涉及到的技术有RabbitMq消息队列,Autofac依赖注入等常用的.net插件。由于公司的发展,业务不断更新,变得复杂起来,对于数据的实时性、存储容量要求也提高了一个新的高度。数据库上下文DbContext设计的是单例模式,基本上告别了多线程高并发的数据读写能力,看了园子里很多大神的博客,均为找到适合自己当前需求的DbContext的管理方式。总结目前主要的管理方式: 1)DbContext单例模式(长连接)。即公司之前的设计。很明显,这种设计方式无法支持多线程同步数据操作。报各种错误,最常见的,比如:集合已修改,无法进行枚举操作。—弃用 2)Using模式(短连接)。这种模式适合一些对于外键,导航属性不经常使用的场合,由于导航属性是放在上下文缓存中的,一旦上下文释放掉,导航属性就为null。当然,也尝试了其他大神的做法,比如,在上下文释放之前转换为 ToList或者使用饥饿加载的方式(ps:这种方式很不灵活,你总不可能遇到一个类类型就去利用反射加载找到它具有的导航属性吧或者直接InCluding),这些方法依旧没有办法解决目前的困境。也尝试这直接赋值给一个定义的同类 型的变量,但是对于这种带导航的导航的复杂类的深拷贝,没有找到合适的路子,有知道的可以告诉我,非常感谢! 以上两种方式及网上寻找的其他方式都没有解决我的问题。这里先上一下之前的Repository:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
1 using System.Data.Entity; 2 using System.Data.Entity.Validation; 3 4 namespace MM.Data.Library.Entityframework 5 { 6 public class EntityFrameworkRepositoryContext : RepositoryContext, IEntityFrameworkRepositoryContext 7 { 8 protected DbContext container; 9 10 public EntityFrameworkRepositoryContext(DbContext container) 11 { 12 this.container = container; 13 } 14 15 public override void RegisterNew<TAggregateRoot>(TAggregateRoot obj) 16 { 17 this.container.Set<TAggregateRoot>().Add(obj); 18 this.IsCommit = false; 19 } 20 21 public override void RegisterModified<TAggregateRoot>(TAggregateRoot obj) 22 { 23 if (this.container.Entry<TAggregateRoot>(obj).State == EntityState.Detached) 24 { 25 this.container.Set<TAggregateRoot>().Attach(obj); 26 } 27 this.container.Entry<TAggregateRoot>(obj).State = EntityState.Modified; 28 this.IsCommit = false; 29 } 30 31 public override void RegisterDeleted<TAggregateRoot>(TAggregateRoot obj) 32 { 33 this.container.Set<TAggregateRoot>().Remove(obj); 34 this.IsCommit = false; 35 } 36 37 public override void Rollback() 38 { 39 this.IsCommit = false; 40 } 41 42 protected override void DoCommit() 43 { 44 if (!IsCommit) 45 { 46 //var count = container.SaveChanges(); 47 //IsCommit = true; 48 try 49 { 50 var count = container.SaveChanges(); 51 IsCommit = true; 52 } 53 catch (DbEntityValidationException dbEx) 54 { 55 foreach (var validationErrors in dbEx.EntityValidationErrors) 56 { 57 foreach (var validationError in validationErrors.ValidationErrors) 58 { 59 } 60 } 61 IsCommit = false; 62 } 63 } 64 } 65 66 public System.Data.Entity.DbContext DbContext 67 { 68 get { return container; } 69 } 70 71 public override void Dispose() 72 { 73 if (container != null) 74 container.Dispose(); 75 } 76 } 77 } |
View Code 2.设计思路及方法 从上下文的单例模式来看,所要解决的问题无非就是在多线程对数据库写操作上面。只要在这上面做手脚,问题应该就能引刃而解。我的想法是将所有的要修改的数据分别放入UpdateList,InsertList,DeleteList三个集合中去,然后提交到数据库保存。至于DbContext的管理,通过一个数据库工厂获取,保证每一个数据库的连接都是唯一的,不重复的(防止发生类似这种错误:正在创建模型,此时不可使用上下文。),用的时候直接去Factory拿。等到数据库提交成功后,清空集合数据。看起来,实现起来很容易,但是因为还涉及到其他技术,比如Redis。所以实现过程费劲。也许我的能力还差很多。总之,废话不多说,直接上部分实现代码: 数据库上下文建立工厂:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
1 /// <summary> 2 /// 数据库建立工厂 3 /// Modify By: 4 /// Modify Date: 5 /// Modify Reason: 6 /// </summary> 7 public sealed class DbFactory 8 { 9 public static IDbContext GetCurrentDbContext(string connectstring,string threadName) 10 { 11 lock (threadName) 12 { 13 //CallContext:是线程内部唯一的独用的数据槽(一块内存空间) 14 //传递Context进去获取实例的信息,在这里进行强制转换。 15 var Context = CallContext.GetData("Context") as IDbContext; 16 17 if (Context == null) //线程在内存中没有此上下文 18 { 19 var Scope = UnitoonIotContainer.Container.BeginLifetimeScope(); 20 //如果不存在上下文 创建一个(自定义)EF上下文 并且放在数据内存中去 21 Context = Scope.Resolve<IDbContext>(new NamedParameter("connectionString", connectstring)); 22 CallContext.SetData("Context", Context); 23 } 24 else 25 { 26 27 if (!Context.ConnectionString.Equals(connectstring)) 28 { 29 var Scope = UnitoonIotContainer.Container.BeginLifetimeScope(); 30 //如果不存在上下文 创建一个(自定义)EF上下文 并且放在数据内存中去 31 Context = Scope.Resolve<IDbContext>(new NamedParameter("connectionString", connectstring)); 32 CallContext.SetData("Context", Context); 33 } 34 } 35 return Context; 36 } 37 } 38 39 } |
View Code Repository:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 |
1 public class RepositoryBase<T, TContext> : IRepositoryBase<T> where T : BaseEntity 2 3 where TContext : ContextBase, IDbContext, IDisposable, new() 4 { 5 public List<T> InsertList { get; set; } 6 public List<T> DeleteList { get; set; } 7 public List<T> UpdateList { get; set; } 8 9 #region field 10 11 protected readonly string Connectstring; 12 ///// <summary> 13 ///// </summary> 14 //protected static IDbContext Context; 15 protected IDbContext dbContext; 16 private static readonly ILifetimeScope Scope; 17 public static int xcount = 0; 18 /////// <summary> 19 /////// </summary> 20 //protected readonly DbSet<T> Dbset; 21 22 #endregion 23 24 #region ctor 25 26 static RepositoryBase() 27 { 28 Scope = UnitoonIotContainer.Container.BeginLifetimeScope(); 29 } 30 31 /// <summary> 32 /// 使用默认连接字符串name=connName 33 /// </summary> 34 public RepositoryBase() : this("") 35 { 36 } 37 38 /// <summary> 39 /// 构造函数 40 /// </summary> 41 /// <param name="connectionString">连接字符串</param> 42 public RepositoryBase(string connectionString) 43 { 44 InsertList = new List<T>(); 45 DeleteList = new List<T>(); 46 UpdateList = new List<T>(); 47 48 49 //*****做以下调整,初始化,建立所有数据库连接,保持长连接状态,在用的时候去判断使用连接 50 51 52 //todo 待处理 53 54 55 if (string.IsNullOrWhiteSpace(connectionString)) 56 { 57 var name = DataBase.GetConnectionString(Activator.CreateInstance<T>().DbType); 58 //Context= ContextHelper.GetDbContext(Activator.CreateInstance<T>().DbType); 59 connectionString = name; 60 } 61 Connectstring = connectionString; 62 63 // Context = Scope.Resolve<IDbContext>(new NamedParameter("connectionString", Connectstring)); 64 65 //Context = new TContext { ConnectionString = connectionString }; 66 67 68 // Dbset = Context.Set<T>(); 69 70 //var loggerFactory = ((DbContext)Context).GetService<ILoggerFactory>(); 71 //loggerFactory.AddProvider(new DbLoggerProvider(Console.WriteLine)); 72 //loggerFactory.AddConsole(minLevel: LogLevel.Warning); 73 } 74 75 //public RepositoryBase(TContext context) 76 //{ 77 // Context = context; 78 // Dbset = context.Set<T>(); 79 //} 80 81 #endregion 82 83 #region Method 84 85 //public virtual IDbContext GetDbContext(ILifetimeScope scope) 86 //{ 87 88 //} 89 90 #region Check Model 91 92 /// <summary> 93 /// 校正Model 94 /// </summary> 95 protected virtual void ValidModel() 96 { 97 } 98 99 #endregion 100 101 #region Update 102 103 public virtual void Update(T entity) 104 { 105 Check.NotNull(entity, "entity"); 106 UpdateList.Add(entity); 107 //context.Set<T>().Update(entity); 108 } 109 110 public virtual void Update(IEnumerable<T> entities) 111 { 112 Check.NotNull(entities, "entities"); 113 UpdateList.AddRange(entities); 114 } 115 116 #endregion 117 118 #region PageList 119 120 public virtual IEnumerable<T> GetPageList(Expression<Func<T, bool>> where, Expression<Func<T, object>> orderBy, 121 int pageIndex, int pageSize) 122 { 123 //todo 124 } 125 126 #endregion 127 128 #region Insert 129 130 public virtual void Add(T entity) 131 { 132 Check.NotNull(entity, "entity"); 133 //排除已经存在的项(对于多线程没有任何用处) 134 if (!InsertList.Exists(e => e.Equals(entity))) 135 { 136 InsertList.Add(entity); 137 } 138 139 } 140 141 public virtual void Add(IEnumerable<T> entities) 142 { 143 Check.NotNull(entities, "entities"); 144 InsertList.AddRange(entities); 145 } 146 147 public void BulkInsert(IEnumerable<T> entities) 148 { 149 Check.NotNull(entities, "entities"); 150 InsertList.AddRange(entities); 151 } 152 153 #endregion 154 155 #region Delete 156 157 public virtual void Delete(int id) 158 { 159 var entity = GetById(id); 160 Delete(entity); 161 // throw new NotImplementedException("Delete(int id)"); 162 } 163 164 public virtual void Delete(string id) 165 { 166 throw new NotImplementedException("Delete(string id)"); 167 } 168 169 public virtual void Delete(T entity) 170 { 171 Check.NotNull(entity, "entity"); 172 DeleteList.Add(entity); 173 } 174 175 public virtual void Delete(IEnumerable<T> entities) 176 { 177 Check.NotNull(entities, "entities"); 178 foreach (var x1 in DeleteList) 179 { 180 DeleteList.Add(x1); 181 } 182 } 183 184 public virtual void Delete(Expression<Func<T, bool>> where) 185 { 186 var list = DeleteList.Where(where.Compile()); 187 Delete(list); 188 } 189 190 #endregion 191 192 #region Commit 193 194 public int Commit() 195 { 196 ValidModel(); 197 //var x = Activator.CreateInstance<T>(); 198 //Context = ContextHelper.GetDbContext(x.DbType); 199 //using (var scope = UnitoonIotContainer.Container.BeginLifetimeScope()) 200 //{ 201 // var context = scope.Resolve<IDbContext>(new NamedParameter("connectionString", Connectstring)); 202 203 //var loggerFactory = Activator.CreateInstance<ILoggerFactory>();// ((DbContext)context).GetService<ILoggerFactory>(); 204 //loggerFactory.AddProvider(new DbLoggerProvider(Console.WriteLine)); 205 dbContext = DbFactory.GetCurrentDbContext(Connectstring, Thread.CurrentThread.Name); 206 var dbset = dbContext.Set<T>(); 207 if (InsertList != null && InsertList.Any()) 208 { 209 List<T> InsertNewList = InsertList.Distinct(new PropertyComparer<T>("Id")).ToList();//按照特定规则排除重复项 210 dbset.AddRange(InsertNewList); 211 } 212 213 if (DeleteList != null && DeleteList.Any()) 214 DeleteList.ForEach(t => 215 { 216 // Context.Entry(t).State = EntityState.Detached;//将之前上下文跟踪的状态丢弃 217 //dbContext.Entry(t).State = EntityState.Detached;//将之前上下文跟踪的状态丢弃 218 dbset.Attach(t); 219 dbset.Remove(t); 220 }); 221 if (UpdateList != null && UpdateList.Any()) 222 { 223 List<T> UpdateNewList = UpdateList.Distinct(new PropertyComparer<T>("Id")).ToList();//按照特定规则排除重复项 224 UpdateNewList.ForEach(t => 225 { 226 //Context.Entry(t).State = EntityState.Detached;//将之前上下文跟踪的状态丢弃 227 // dbContext.Entry(t).State = EntityState.Detached;//将之前上下文跟踪的状态丢弃 228 dbContext.Entry(t).State = EntityState.Modified; 229 });//.UpdateRange(UpdateNewList); 230 } 231 var result = 0; 232 try 233 { 234 result = dbContext.SaveChanges(); 235 } 236 catch (Exception ex) 237 { 238 239 // throw; 240 } 241 242 if (InsertList != null && InsertList.Any()) 243 InsertList.Clear(); 244 if (DeleteList != null && DeleteList.Any()) 245 DeleteList.Clear(); 246 if (UpdateList != null && UpdateList.Any()) 247 UpdateList.Clear(); 248 return result; 249 //} 250 } 251 252 public async Task<int> CommitAsync() 253 { 254 ValidModel(); 255 //todo 256 257 } 258 259 #endregion 260 261 #region Query 262 public IQueryable<T> Get() 263 { 264 return GetAll().AsQueryable(); 265 } 266 //public virtual T Get(Expression<Func<T, bool>> @where) 267 //{ 268 // using (var scope = UnitoonIotContainer.Container.BeginLifetimeScope()) 269 // { 270 271 // var context = scope.Resolve<IDbContext>(new NamedParameter("connectionString", Connectstring)); 272 // var dbset = context.Set<T>(); 273 // return dbset.FirstOrDefault(where); 274 // } 275 //} 276 277 public virtual async Task<T> GetAsync(Expression<Func<T, bool>> @where) 278 { 279 //todo 280 } 281 282 public virtual T GetById(int id) 283 { 284 throw new NotImplementedException("GetById(int id)"); 285 } 286 287 public virtual async Task<T> GetByIdAsync(int id) 288 { 289 throw new NotImplementedException("GetById(int id)"); 290 } 291 292 public virtual T GetById(string id) 293 { 294 throw new NotImplementedException("GetById(int id)"); 295 } 296 297 public virtual async Task<T> GetByIdAsync(string id) 298 { 299 throw new NotImplementedException("GetById(int id)"); 300 } 301 302 public virtual T Get(Expression<Func<T, bool>> @where)//, params string[] includeProperties 303 { 304 //var scope = UnitoonIotContainer.Container.BeginLifetimeScope(); 305 //{ 306 // var context = scope.Resolve<IDbContext>(new NamedParameter("connectionString", Connectstring)); 307 //Thread.Sleep(50); 308 //lock (Context) 309 { 310 dbContext= DbFactory.GetCurrentDbContext(Connectstring, Thread.CurrentThread.Name); 311 var dbset = dbContext.Set<T>().Where(e => !e.IsDeleted).AsQueryable(); 312 var entity = dbset.FirstOrDefault(where); 313 //test 314 // Context.Entry(entity).State = EntityState.Detached;//将之前上下文跟踪的状态丢弃 315 return entity; 316 } 317 318 319 //} 320 } 321 322 public virtual IEnumerable<T> GetAll() 323 { 324 //Thread.Sleep(50); 325 //lock (Context) 326 { 327 dbContext = DbFactory.GetCurrentDbContext(Connectstring, Thread.CurrentThread.Name); 328 var dbset = dbContext.Set<T>().Where(e => !e.IsDeleted); 329 //test 330 //dbset.ToList().ForEach(t => 331 //{ 332 // Context.Entry(t).State = EntityState.Detached;//将之前上下文跟踪的状态丢弃 333 //}); 334 335 return dbset; 336 } 337 338 339 340 341 //var scope = UnitoonIotContainer.Container.BeginLifetimeScope(); 342 343 // var context = scope.Resolve<IDbContext>(new NamedParameter("connectionString", Connectstring)); 344 345 } 346 347 public async virtual Task<IEnumerable<T>> GetAllAsync() 348 { 349 //todo 350 } 351 352 public virtual IEnumerable<T> GetMany(Expression<Func<T, bool>> where) 353 { 354 //using (var scope = UnitoonIotContainer.Container.BeginLifetimeScope()) 355 //{ 356 // var context = scope.Resolve<IDbContext>(new NamedParameter("connectionString", Connectstring)); 357 358 // var dbset = context.Set<T>(); 359 //Thread.Sleep(50); 360 //lock (Context) 361 { 362 dbContext = DbFactory.GetCurrentDbContext(Connectstring, Thread.CurrentThread.Name); 363 var dbset = dbContext.Set<T>().Where(e => !e.IsDeleted); 364 //test 365 //dbset.ToList().ForEach(t => 366 //{ 367 // Context.Entry(t).State = EntityState.Detached;//将之前上下文跟踪的状态丢弃 368 //}); 369 return dbset.Where(@where).ToList(); 370 } 371 372 //} 373 } 374 375 public virtual async Task<IEnumerable<T>> GetManyAsync(Expression<Func<T, bool>> where) 376 { 377 //todo 378 } 379 380 public virtual IEnumerable<T> IncludeSubSets(params Expression<Func<T, object>>[] includeProperties) 381 { 382 //todo 383 } 384 385 #region navigation 386 /// <summary> 387 /// 加载导航 388 /// </summary> 389 /// <param name="where"></param> 390 /// <param name="includeProperties"></param> 391 /// <returns></returns> 392 //public virtual T Get(Expression<Func<T, bool>> @where, params Expression<Func<T, object>>[] includeProperties) 393 //{ 394 // using (var scope = UnitoonIotContainer.Container.BeginLifetimeScope()) 395 // { 396 397 // var context = scope.Resolve<IDbContext>(new NamedParameter("connectionString", Connectstring)); 398 // var dbset = context.Set<T>(); 399 // var query = includeProperties.Aggregate<Expression<Func<T, object>>, IQueryable<T>>(dbset, 400 // (current, includeProperty) => current.Include(includeProperty)); 401 // return query.FirstOrDefault(where); 402 // } 403 //} 404 405 //public virtual T Get(Expression<Func<T, bool>> @where)//, params string[] includeProperties 406 //{ 407 // //反射获取导航 408 // var includeProperties = 409 // Activator.CreateInstance<T>().GetType().GetProperties().Where(p => p.GetMethod.IsVirtual).Select(e => e.Name).ToArray(); 410 411 //todo 412 //} 413 #endregion 414 public List<TDynamicEntity> GetDynamic<TTable, TDynamicEntity>(Expression<Func<TTable, object>> selector, 415 Func<object, TDynamicEntity> maker) where TTable : class 416 { 417 //todo 418 } 419 420 public List<TDynamicEntity> GetDynamic<TTable, TDynamicEntity>(Func<TTable, object> selector, 421 Func<object, TDynamicEntity> maker) where TTable : class 422 { 423 //todo 424 425 } 426 427 #endregion 428 429 #region Count 430 431 public virtual async Task<int> CountAsync() 432 { 433 //todo 434 } 435 436 public virtual async Task<int> CountByAsync(Expression<Func<T, bool>> where) 437 { 438 //todo 439 } 440 441 #endregion 442 443 #region Exists 444 445 public virtual bool Exists(string id) 446 { 447 throw new NotImplementedException(); 448 } 449 450 public virtual bool Exists(int id) 451 { 452 throw new NotImplementedException(); 453 } 454 455 public virtual async Task<bool> ExistsAsync(string id) 456 { 457 throw new NotImplementedException(); 458 } 459 460 public virtual async Task<bool> ExistsAsync(int id) 461 { 462 throw new NotImplementedException(); 463 } 464 465 public virtual bool Exists(Expression<Func<T, bool>> @where) 466 { 467 throw new NotImplementedException(); 468 } 469 470 public virtual async Task<bool> ExistsAsync(Expression<Func<T, bool>> @where) 471 { 472 throw new NotImplementedException(); 473 } 474 475 #endregion 476 477 478 #endregion 479 } |
http://blog.csdn.net/wodeai1235/article/details/54923072
View Details这些多线程的问题,有些来源于各大网站、有些来源于自己的思考。可能有些问题网上有、可能有些问题对应的答案也有、也可能有些各位网友也都看过,但是本文写作的重心就是所有的问题都会按照自己的理解回答一遍,不会去看网上的答案,因此可能有些问题讲的不对,能指正的希望大家不吝指教。 40个问题汇总 1、多线程有什么用? 一个可能在很多人看来很扯淡的一个问题:我会用多线程就好了,还管它有什么用?在我看来,这个回答更扯淡。所谓”知其然知其所以然”,”会用”只是”知其然”,”为什么用”才是”知其所以然”,只有达到”知其然知其所以然”的程度才可以说是把一个知识点运用自如。OK,下面说说我对这个问题的看法: (1)发挥多核CPU的优势 随着工业的进步,现在的笔记本、台式机乃至商用的应用服务器至少也都是双核的,4核、8核甚至16核的也都不少见,如果是单线程的程序,那么在双核CPU上就浪费了50%,在4核CPU上就浪费了75%。单核CPU上所谓的”多线程”那是假的多线程,同一时间处理器只会处理一段逻辑,只不过线程之间切换得比较快,看着像多个线程”同时”运行罢了。多核CPU上的多线程才是真正的多线程,它能让你的多段逻辑同时工作,多线程,可以真正发挥出多核CPU的优势来,达到充分利用CPU的目的。 (2)防止阻塞 从程序运行效率的角度来看,单核CPU不但不会发挥出多线程的优势,反而会因为在单核CPU上运行多线程导致线程上下文的切换,而降低程序整体的效率。但是单核CPU我们还是要应用多线程,就是为了防止阻塞。试想,如果单核CPU使用单线程,那么只要这个线程阻塞了,比方说远程读取某个数据吧,对端迟迟未返回又没有设置超时时间,那么你的整个程序在数据返回回来之前就停止运行了。多线程可以防止这个问题,多条线程同时运行,哪怕一条线程的代码执行读取数据阻塞,也不会影响其它任务的执行。 (3)便于建模 这是另外一个没有这么明显的优点了。假设有一个大的任务A,单线程编程,那么就要考虑很多,建立整个程序模型比较麻烦。但是如果把这个大的任务A分解成几个小任务,任务B、任务C、任务D,分别建立程序模型,并通过多线程分别运行这几个任务,那就简单很多了。 2、创建线程的方式 比较常见的一个问题了,一般就是两种: (1)继承Thread类 (2)实现Runnable接口 至于哪个好,不用说肯定是后者好,因为实现接口的方式比继承类的方式更灵活,也能减少程序之间的耦合度,面向接口编程也是设计模式6大原则的核心。 3、start()方法和run()方法的区别 只有调用了start()方法,才会表现出多线程的特性,不同线程的run()方法里面的代码交替执行。如果只是调用run()方法,那么代码还是同步执行的,必须等待一个线程的run()方法里面的代码全部执行完毕之后,另外一个线程才可以执行其run()方法里面的代码。 4、Runnable接口和Callable接口的区别 有点深的问题了,也看出一个Java程序员学习知识的广度。 Runnable接口中的run()方法的返回值是void,它做的事情只是纯粹地去执行run()方法中的代码而已;Callable接口中的call()方法是有返回值的,是一个泛型,和Future、FutureTask配合可以用来获取异步执行的结果。 这其实是很有用的一个特性,因为多线程相比单线程更难、更复杂的一个重要原因就是因为多线程充满着未知性,某条线程是否执行了?某条线程执行了多久?某条线程执行的时候我们期望的数据是否已经赋值完毕?无法得知,我们能做的只是等待这条多线程的任务执行完毕而已。而Callable+Future/FutureTask却可以获取多线程运行的结果,可以在等待时间太长没获取到需要的数据的情况下取消该线程的任务,真的是非常有用。 5、CyclicBarrier和CountDownLatch的区别 两个看上去有点像的类,都在java.util.concurrent下,都可以用来表示代码运行到某个点上,二者的区别在于: (1)CyclicBarrier的某个线程运行到某个点上之后,该线程即停止运行,直到所有的线程都到达了这个点,所有线程才重新运行;CountDownLatch则不是,某线程运行到某个点上之后,只是给某个数值-1而已,该线程继续运行 (2)CyclicBarrier只能唤起一个任务,CountDownLatch可以唤起多个任务 (3)CyclicBarrier可重用,CountDownLatch不可重用,计数值为0该CountDownLatch就不可再用了 6、Volatile关键字的作用 一个非常重要的问题,是每个学习、应用多线程的Java程序员都必须掌握的。理解volatile关键字的作用的前提是要理解Java内存模型,这里就不讲Java内存模型了,可以参见第31点,volatile关键字的作用主要有两个: (1)多线程主要围绕可见性和原子性两个特性而展开,使用volatile关键字修饰的变量,保证了其在多线程之间的可见性,即每次读取到volatile变量,一定是最新的数据 (2)代码底层执行不像我们看到的高级语言—-Java程序这么简单,它的执行是Java代码–>字节码–>根据字节码执行对应的C/C++代码–>C/C++代码被编译成汇编语言–>和硬件电路交互,现实中,为了获取更好的性能JVM可能会对指令进行重排序,多线程下可能会出现一些意想不到的问题。使用volatile则会对禁止语义重排序,当然这也一定程度上降低了代码执行效率 从实践角度而言,volatile的一个重要作用就是和CAS结合,保证了原子性,详细的可以参见java.util.concurrent.atomic包下的类,比如AtomicInteger。 7、什么是线程安全 又是一个理论的问题,各式各样的答案有很多,我给出一个个人认为解释地最好的:如果你的代码在多线程下执行和在单线程下执行永远都能获得一样的结果,那么你的代码就是线程安全的。 这个问题有值得一提的地方,就是线程安全也是有几个级别的: (1)不可变 像String、Integer、Long这些,都是final类型的类,任何一个线程都改变不了它们的值,要改变除非新创建一个,因此这些不可变对象不需要任何同步手段就可以直接在多线程环境下使用 (2)绝对线程安全 不管运行时环境如何,调用者都不需要额外的同步措施。要做到这一点通常需要付出许多额外的代价,Java中标注自己是线程安全的类,实际上绝大多数都不是线程安全的,不过绝对线程安全的类,Java中也有,比方说CopyOnWriteArrayList、CopyOnWriteArraySet (3)相对线程安全 相对线程安全也就是我们通常意义上所说的线程安全,像Vector这种,add、remove方法都是原子操作,不会被打断,但也仅限于此,如果有个线程在遍历某个Vector、有个线程同时在add这个Vector,99%的情况下都会出现ConcurrentModificationException,也就是fail-fast机制。 (4)线程非安全 这个就没什么好说的了,ArrayList、LinkedList、HashMap等都是线程非安全的类 8、Java中如何获取到线程dump文件 死循环、死锁、阻塞、页面打开慢等问题,打线程dump是最好的解决问题的途径。所谓线程dump也就是线程堆栈,获取到线程堆栈有两步: (1)获取到线程的pid,可以通过使用jps命令,在Linux环境下还可以使用ps -ef | grep java (2)打印线程堆栈,可以通过使用jstack […]
View Details