推荐.Net、C# 逆向反编译四大工具利器
转自:https://blog.csdn.net/kongwei521/article/details/54927689 在项目开发过程中,估计也有人和我遇到过同样的经历:运行环境出现了重大Bug亟需解决、或者由于电脑挂了、旧代码覆盖新代码,而在这种情况下,我们不能直接在当前的代码中修改这个Bug然后发布,这会导致更严重的问题,因为相当于版本回退了。还有电脑挂了代码整个都没有,这种情况下 我们只能只能利用一些逆向的技巧和工具了 来解析在服务器发布好的dll。那么你只是单纯的修改一个.Net程序集中的某个方法或功能,而且这个程序集还是出自于你自己或你所在团队之手,这实在是一件非常容易的事情,这和破解别人的程序完全不同,你不会遇到无法破解的加密算法,也不会遇到让人恶心的加壳混淆。所以我要把用过的工具一个个的列出来总结一下。 推荐四大发编译工具 1:.Net Reflector 【收费】 一提起.Net逆向,其实很多人第一反应都是Reflector这款神器,这一方面是由于Reflector良好的用户体验和强大的插件功能,另一方面要归功于Reflector堪称完美的智能反编译能力,使用它不仅能看到反编译后的IL源码甚至能直接反编译出C#源码,而且和编写时的代码几无二致,如果需要还可以直接另存为工程文件用Visual Studio打开,不过现在已经收费了,所以老司机都选择破解版,有钱人选择正版。 破解地址就不在这里放出,大家自行搜索. 使用方法:可以直接把dll、exe拖放到左侧,或者文件选择选择 官方网址:http://www.red-gate.com/products/dotnet-development/reflector/ 2:ILSpy/dnSpy 【免费】 ILSpy是唯一免费且开源的.NET反编译器,它基于MIT许可证发布。ILSpy的代码生成和语法高亮功能做的非常好。对于反编译的程序集,它既可以将其保存在一个文件中,也可以为所有文件创建一个项目。ILSpy是一个独立的工具,没有Visual Studio集成。,ILSpy 是为了完全替代收费的Reflector而生,它是由 iCSharpCode 团队出品,这个团队开发了著名的 SharpDevelop 。ILSpy 完全开源,ILSpy的使用和上面的Reflector完全类似,可以直接把dll、exe拖放到左侧,或者文件选择选择。 官方网址:http://ilspy.net/ ILSPY还有一款同门师弟,感觉比ILSPY还强大 dnSpy is a .NET assembly editor, decompiler, and debugger forked from ILSpy * Assembly editor * Decompiler * Debugger * Tabs and tab groups * Themes (blue, dark, light and high contrast) If you want to help, fork the project and send pull requests. Latest release: https://github.com/0xd4d/dnSpy/releases Latest build: https://ci.appveyor.com/project/0xd4d/dnspy/build/artifacts 3:JetBrains dotPeek【免费】 JetBrains是捷克的一家软件开发公司,出品了大量著名的开发工具,包括:IntelliJ IDEA、PHPStorm、ReSharper、TeamCity、YouTrack等等,每一款产品都如雷贯耳。dotPeek 是 JetBrains 开发的一款.Net反编译工具,是.Net工具套件中的一个相比于前面几款工具来说,dotPeek算比较小众的一款,它生成的代码质量很高,它还会尝试到源代码服务器上抓取代码。DotPeek的导航功能和快捷键非常便捷。它还能精确查找符号的使用,同时支持插件。DotPeek不能与Visual Studio集成。个人感觉它最大的特色就是Visual Studio风格,这对于那些长期在Visual Studio下进行开发的人来说应该更亲切一点。 官方网址:http://www.jetbrains.com/decompiler/ 4:Telerik JustDecompile 【需要输入信息安装】不喜欢这个就卸载了 Telerik JustDecompile是一个免费的.NET反编译器,但是有商业化支持。它生成的代码质量也很高。它可以为反编译程序集得到的代码创建一个项目。JustDecompile提供了健壮的查找功能,能够支持全文查找和符号使用查找。它还有一个插件系统,目前在Telerik的网站上有两个可用的扩展。JustDecompile不能与Visual Studio集成。 […]
View Details企业级的 UI 设计语言和 React 实现 Ant Design
授权协议: MIT 开发语言: JavaScript HTML/CSS 操作系统: 跨平台 开发厂商:阿里巴巴 收录时间: 2015-07-27 提 交 者:叶秀兰 Ant Design 是蚂蚁金服开发和正在使用的一套企业级的前端设计语言和基于 React 的前端框架实现。 特性 企业级金融产品的交互语言和视觉体系。 丰富实用的 React UI 组件。 基于 React 的组件化开发模式。 背靠 npm 生态圈。 基于 webpack 的调试构建方案,支持 ES6。 示例
|
1 2 3 4 |
<span class="hljs-keyword">var</span> antd = <span class="hljs-built_in">require</span>(<span class="hljs-string">'antd'</span>); <span class="hljs-keyword">var</span> Datepicker = antd.Datepicker; React.render(<span class="xml"><span class="hljs-tag"><<span class="hljs-name">Datepicker</span> /></span>, mountNode);</span> |
开发说明 本地调试
|
1 |
<span class="hljs-meta">$</span><span class="bash"> npm start</span> |
然后访问 http://127.0.0.1:8000 。 网站部署
|
1 |
<span class="hljs-meta">$</span><span class="bash"> npm run deploy</span> |
版本构建
|
1 |
<span class="hljs-meta">$</span><span class="bash"> npm run release</span> |
from:https://www.oschina.net/p/ant-design
View Details8分钟学会使用AutoMapper
一.什么是AutoMapper与为什么用它。 它是一种对象与对象之间的映射器,让AutoMapper有意思的就是在于它提供了一些将类型A映射到类型B这种无聊的实例,只要B遵循AutoMapper已经建立的惯例,那么大多数情况下就可以进行相互映射了。 二.如何使用? 直接nuget install-package automapper 简单到不能再简单了。 三.入门 定义了连个简单的Model:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
public class Destination { public string name { get; set; } public string InfoUrl { get; set; } } public class Source { public string name { get; set; } public string InfoUrl { get; set; } public string aa { get; set; } } |
|
1 2 3 4 5 6 7 8 9 10 11 |
static void Main(string[] args) { Destination des = new Destination() { InfoUrl = "www.cnblogs.com/zaranet", name = "张子浩" }; Mapper.Initialize(x => x.CreateMap<Destination, Source>()); Source source = AutoMapper.Mapper.Map<Source>(des); Console.WriteLine(source.InfoUrl); } |
Initialize方法是Mapper的初始化,里面可以写上CreateMap表达式,具体是谁和谁进行匹配。在之后就可以直接进行一个获取值的过程了,非常的简单。 四.映射前后操作 偶尔有的时候你可能需要在映射的过程中,你需要执行一些逻辑,这是非常常见的事情,所以AutoMapper给我们提供了BeforeMap和AfterMap两个函数。
|
1 2 3 |
Mapper.Initialize(x => x.CreateMap<Destination, Source>().BeforeMap( (src,dest)=>src.InfoUrl ="https://"+src.InfoUrl).AfterMap( (src,dest)=>src.name="真棒"+src.name)); |
其中呢,src是Destination对象,dest是Source,你呢就可以用这两个对象去获取里面的值,说白了这就是循环去找里面的值了。 五.条件映射
|
1 |
Mapper.Initialize(x => x.CreateMap<Destination, Source>().ForMember(dest => dest.InfoUrl,opt => opt.Condition(dest => dest.InfoUrl == "www.cnblogs.com/zaranet1")).ForMember(...(.ForMember(...)))); |
在条件映射中,通过ForMember函数,参数是一个委托类型Fun<>,其里面呢也是可以进行嵌套的,但一般来说一个就够用了。 六.AutoMapper配置 初始化配置是非常受欢迎的,每个领域都应该配置一次。
|
1 2 3 4 5 |
//初始化配置文件 Mapper.Initialize(cfg => { cfg.CreateMap<Aliens, Person>(); }); |
但是像这种情况呢,如果是多个映射,那么我们只能用Profile来配置,组织你的映射配置,并将配置放置到构造函数中(这种情况是5.x以上的版本),一个是以下的版本,已经被淘汰了。 5.0及以上版本:
|
1 2 3 4 5 6 7 |
public class AliensPersonProfile : Profile { public AliensPersonProfile() { CreateMap<Destination, Source>(); } } |
5.0以下版本(在早期版本中,使用配置方法而不是构造函数。 从版本5开始,Configure()已经过时。 它将在6.0中被删除。)
|
1 2 3 4 5 6 7 |
public class OrganizationProfile : Profile { protected override void Configure() { CreateMap<Foo, FooDto>(); } } |
然后在程序启动的时候初始化即可。
|
1 |
Mapper.Initialize(x=>x.AddProfile<AliensPersonProfile>()); |
七.AutoMapper的最佳实践 上文中已经说到了AutoMapper的简单映射,但是在实际项目中,我们应该有很多类进行映射,这么多的映射应该怎么组织,这是一个活生生的问题,这成为主映射器。 在主映射器中,组织了多个小映射器,Configuration为我们的静态配置入口类;Profiles文件夹为我们所有Profile类的文件夹。如果是MVC,我们需要在Global中调用,那我的这个是控制台的。
|
1 2 3 4 5 6 7 8 |
public static void Configure() { Mapper.Initialize(cfg => { cfg.AddProfile<DestinationSourceProfile>(); cfg.AddProfile(new StudentSourceProfile()); }); } |
其中添加子映射,可以用以上两种方式。
|
1 2 3 4 |
public void Configuration(IAppBuilder app) { AutoMapperConfiguration.Configure(); } |
八.指定映射字段 在实际业务环境中,你不可能说两个类的字段是一 一 对应的,这个时候我们就要对应它们的映射关系。
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public class CalendarEvent { public DateTime Date { get; set; } public string Title { get; set; } } public class CalendarEventForm { public DateTime EventDate { get; set; } public int EventHour { get; set; } public int EventMinute { get; set; } public string DisplayTitle { get; set; } } |
在这两个类中,CalendarEvent的Date将被拆分为CalendarEventForm的日期、时、分三个字段,Title也将对应DisplayTitle字段,那么相应的Profile定义如下:
|
1 2 3 4 5 6 7 8 9 10 11 |
public class CalendarEventProfile : Profile { public CalendarEventProfile() { CreateMap<CalendarEvent, CalendarEventForm>() .ForMember(dest => dest.EventDate, opt => opt.MapFrom(src => src.Date.Date)) .ForMember(dest => dest.EventHour, opt => opt.MapFrom(src => src.Date.Hour)) .ForMember(dest => dest.EventMinute, opt => opt.MapFrom(src => src.Date.Minute)) .ForMember(dest => dest.DisplayTitle, opt => opt.MapFrom(src => src.Title)); } } |
main方法通过依赖注入,开始映射过程,下图是代码和图。
|
1 2 3 4 5 6 7 8 9 10 11 |
static void Main(string[] args) { CalendarEvent calendar = new CalendarEvent() { Date = DateTime.Now, Title = "Demo Event" }; AutoMapperConfiguration.Configure(); CalendarEventForm calendarEventForm = Mapper.Map<CalendarEventForm>(calendar); Console.WriteLine(calendarEventForm); } |
那么最后呢,如果是反向的映射,一定回缺少属性,那么就你就可以obj.属性进行赋值。 附AutoHelper封装类
|
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 |
/// <summary> /// AutoMapper扩展帮助类 /// </summary> public static class AutoMapperHelper { /// <summary> /// 类型映射 /// </summary> public static T MapTo<T>(this object obj) { if (obj == null) return default(T); Mapper.CreateMap(obj.GetType(), typeof(T)); return Mapper.Map<T>(obj); } /// <summary> /// 集合列表类型映射 /// </summary> public static List<TDestination> MapToList<TDestination>(this IEnumerable source) { foreach (var first in source) { var type = first.GetType(); Mapper.CreateMap(type, typeof(TDestination)); break; } return Mapper.Map<List<TDestination>>(source); } /// <summary> /// 集合列表类型映射 /// </summary> public static List<TDestination> MapToList<TSource, TDestination>(this IEnumerable<TSource> source) { //IEnumerable<T> 类型需要创建元素的映射 Mapper.CreateMap<TSource, TDestination>(); return Mapper.Map<List<TDestination>>(source); } /// <summary> /// 类型映射 /// </summary> public static TDestination MapTo<TSource, TDestination>(this TSource source, TDestination destination) where TSource : class where TDestination : class { if (source == null) return destination; Mapper.CreateMap<TSource, TDestination>(); return Mapper.Map(source, destination); } /// <summary> /// DataReader映射 /// </summary> public static IEnumerable<T> DataReaderMapTo<T>(this IDataReader reader) { Mapper.Reset(); Mapper.CreateMap<IDataReader, IEnumerable<T>>(); return Mapper.Map<IDataReader, IEnumerable<T>>(reader); } } |
from:https://www.cnblogs.com/ZaraNet/p/10000311.html
View DetailsVS Code修改系统界面和编辑面板字体大小
描述 Linux下新安装的VS Code可能字体很小,包括系统字体(标题栏,工具栏、状态栏)和编辑面板的字体很小。 修改 Ctrl + Shitf + p,输入 settings,选择打开那个JSON的系统配置文件
|
1 2 3 4 |
{ "editor.fontSize": 15, "window.zoomLevel": 1.5 } |
修改这两个值即可,第一个是编辑面板的,第二个是系统界面的。 from:https://blog.csdn.net/chenbetter1996/article/details/85166528
View DetailsPowerDesigner导出word模版
模板下载1 模板下载2 解压至:C:\Program Files (x86)\Sybase\PowerDesigner 15\Resource Files\Report Templates 即可 感谢http://blog.csdn.net/ferry_passion/article/details/8948456的作者 from:https://www.cnblogs.com/live365wang/p/4968415.html
View DetailsReSharper2018破解详细方法
下载地址: 主程序官网下载链接:https://download.jetbrains.com/resharper/ReSharperUltimate.2018.3.3/JetBrains.ReSharperUltimate.2018.3.3.exe 2018.3.x破解补丁:https://files.cnblogs.com/files/simadi/Resharper2018.2Crack.7z 安装破解方法 1.先安装好Resharper; 2.下载完补丁后解压,以管理员身份运行Patch.cmd,如下图所示,即破解成功: 3.打开VS,打开ReSharper的注册窗口:ReSharper->Help->License Information… 4.剩余99999天,够你用200多年了吧! from:https://www.cnblogs.com/simadi/p/10412702.html
View Detailsis_uploaded_file总是返回false的问题
is_uploaded_file ile总是返回false,根据以下方法进行检查,全部检查通过。
|
1 2 3 4 5 6 |
1,是否通过http协议上传。 2,form中是否有 enctype="multipart/form-data"。 3,上传文件是否超出了规定的大小。 4,存放上传文件的文件夹是否存在,上传的文件夹是否具有写权限。 5,上传文件应该是使用move<span class="hljs-emphasis">_uploaded_</span>file()这个函数吧! 6,请确保$_FILES[<span class="hljs-string">"upload"</span>][<span class="hljs-symbol">'error'</span>] = 0; |
最后,找到一篇帖子, 将文件名用realpath函数过滤一下即可。
|
1 |
<span class="hljs-meta">is_uploaded_file(realpath($</span><span class="bash">file[<span class="hljs-string">'tmp_name'</span>]))</span> |
原文链接:http://www.xiumu.org/other/under-the-iis-is_uploaded_file-always-returns-false.shtml from:https://my.oschina.net/qii/blog/400692?p=1
View Detailsjava:bytes[]转long的三种方式
bytes[] 到数字类型的转换是个经常用到的代码,解决方式也不止一种,最近需要将bytes[]转为long,有机会深入了解了一下,此文做个总结。 java代码实现 如果不想借助任何已经有的类,完全可以自己实现这段代码,如下:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
/** * 将字节数组转为long<br> * 如果input为null,或offset指定的剩余数组长度不足8字节则抛出异常 * @param input * @param offset 起始偏移量 * @param littleEndian 输入数组是否小端模式 * @return */ public static long longFrom8Bytes(byte[] input, int offset, boolean littleEndian){ long value=0; // 循环读取每个字节通过移位运算完成long的8个字节拼装 for(int count=0;count<8;++count){ int shift=(littleEndian?count:(7-count))<<3; value |=((long)0xff<< shift) & ((long)input[offset+count] << shift); } return value; } |
借助java.nio.ByteBuffer实现 java.nio.ByteBuffer 本身就有getLong,getInt,getFloat….方法,只要将byte[]转换为ByteBuffer就可以实现所有primitive类型的数据读取,参见javadoc。
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
/** * 利用 {@link java.nio.ByteBuffer}实现byte[]转long * @param input * @param offset * @param littleEndian 输入数组是否小端模式 * @return */ public static long bytesToLong(byte[] input, int offset, boolean littleEndian) { // 将byte[] 封装为 ByteBuffer ByteBuffer buffer = ByteBuffer.wrap(input,offset,8); if(littleEndian){ // ByteBuffer.order(ByteOrder) 方法指定字节序,即大小端模式(BIG_ENDIAN/LITTLE_ENDIAN) // ByteBuffer 默认为大端(BIG_ENDIAN)模式 buffer.order(ByteOrder.LITTLE_ENDIAN); } return buffer.getLong(); } |
借助java.io.DataInputStream实现 java.io.DataInputStream 同样提供了readLong,readLong,readLong….方法,只要将byte[]转换为DataInputStream就可以实现所有primitive类型的数据读取,参见javadoc。 完整测试代码 下面的Junit 测试代码计算String 的MD5校验码(16 bytes),然后使用上述方式分别将16 bytes转换为2个long(大端模式)然后以16进制模式输出结果,以验证三种方式一致性。
|
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 |
package net.gdface.facelog; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import org.junit.Test; public class TestSerialVersionUID { /** * 生成MD5校验码 * * @param source * @return */ static public byte[] getMD5(byte[] source) { if (null==source) return null; try { MessageDigest md = MessageDigest.getInstance("MD5"); return md.digest(source); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; } /** * 将16位byte[] 转换为32位的HEX格式的字符串String * * @param buffer * @return */ static public String toHex(byte buffer[]) { if (null==buffer) return null; StringBuffer sb = new StringBuffer(buffer.length * 2); for (int i = 0; i < buffer.length; i++) { sb.append(Character.forDigit((buffer[i] & 240) >> 4, 16)); sb.append(Character.forDigit(buffer[i] & 15, 16)); } return sb.toString(); } /** * 将字节数组转为long<br> * 如果input为null,或offset指定的剩余数组长度不足8字节则抛出异常 * @param input * @param offset 起始偏移量 * @param littleEndian 输入数组是否小端模式 * @return */ public static long longFrom8Bytes(byte[] input, int offset, boolean littleEndian){ if(offset <0 || offset+8>input.length) throw new IllegalArgumentException(String.format("less than 8 bytes from index %d is insufficient for long",offset)); long value=0; for(int count=0;count<8;++count){ int shift=(littleEndian?count:(7-count))<<3; value |=((long)0xff<< shift) & ((long)input[offset+count] << shift); } return value; } /** * 利用 {@link java.nio.ByteBuffer}实现byte[]转long * @param input * @param offset * @param littleEndian 输入数组是否小端模式 * @return */ public static long bytesToLong(byte[] input, int offset, boolean littleEndian) { if(offset <0 || offset+8>input.length) throw new IllegalArgumentException(String.format("less than 8 bytes from index %d is insufficient for long",offset)); ByteBuffer buffer = ByteBuffer.wrap(input,offset,8); if(littleEndian){ // ByteBuffer.order(ByteOrder) 方法指定字节序,即大小端模式(BIG_ENDIAN/LITTLE_ENDIAN) // ByteBuffer 默认为大端(BIG_ENDIAN)模式 buffer.order(ByteOrder.LITTLE_ENDIAN); } return buffer.getLong(); } @Test public void test() throws IOException { String input="net.gdface.facelog.dborm.person.FlPersonBeanBase"; byte[] md5 = getMD5(input.getBytes()); System.out.printf("md5 [%s]\n",toHex(md5)); // 三种方式运算结果对比验证 DataInputStream dataInput = new DataInputStream(new ByteArrayInputStream(md5)); long l1 = dataInput.readLong(); long l2 = dataInput.readLong(); System.out.printf("l1=0x%x l2=0x%x,DataInputStream\n", l1,l2); long ln1 = bytesToLong(md5,0, false); long ln2 = bytesToLong(md5,8, false); System.out.printf("ln1=0x%x ln2=0x%x,ByteBuffer\n", ln1,ln2); long ll1 = longFrom8Bytes(md5,0, false); long ll2 = longFrom8Bytes(md5,8, false); System.out.printf("ll1=0x%x ll2=0x%x\n", ll1,ll2); } } |
输出结果 md5 [39627933ceeebf2740e1f822921f5837] l1=0x39627933ceeebf27 l2=0x40e1f822921f5837,DataInputStream ln1=0x39627933ceeebf27 ln2=0x40e1f822921f5837,,ByteBuffer ll1=0x39627933ceeebf27 ll2=0x40e1f822921f5837 参考资料 《Java 中 byte、byte 数组和 int、long 之间的转换》 from:https://blog.csdn.net/10km/article/details/77435659
View DetailsJava中四种线程安全的单例模式实现方式
第一种:饿汉模式(线程安全)
|
1 2 3 4 5 6 7 8 9 10 11 12 |
public class Single2 { private static Single2 instance = new Single2(); private Single2(){ System.out.println("Single2: " + System.nanoTime()); } public static Single2 getInstance(){ return instance; } } |
第二种:懒汉模式 (如果方法没有synchronized,则线程不安全)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
public class Single3 { private static Single3 instance = null; private Single3(){ System.out.println("Single3: " + System.nanoTime()); } public static synchronized Single3 getInstance(){ if(instance == null){ instance = new Single3(); } return instance; } } |
第三种:懒汉模式改良版(线程安全,使用了double-check,即check-加锁-check,目的是为了减少同步的开销)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
public class Single4 { private volatile static Single4 instance = null; private Single4(){ System.out.println("Single4: " + System.nanoTime()); } public static Single4 getInstance(){ if(instance == null){ synchronized (Single4.class) { if(instance == null){ instance = new Single4(); } } } return instance; } } |
第四种:利用私有的内部工厂类(线程安全,内部类也可以换成内部接口,不过工厂类变量的作用域要改为public了。)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
public class Singleton { private Singleton(){ System.out.println("Singleton: " + System.nanoTime()); } public static Singleton getInstance(){ return SingletonFactory.singletonInstance; } private static class SingletonFactory{ private static Singleton singletonInstance = new Singleton(); } } |
from:https://my.oschina.net/yangchunlian/blog/1607947
View Details用 wait-notify 写一段代码来解决生产者-消费者问题
在同步块中调用 wait() 和 notify()方法,如果阻塞,通过循环来测试等待条件。请参考答案中的示例代码。 【生产者】
|
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 |
import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger; public class Producer implements Runnable { private final Vector sharedQueue; private final int SIZE; public Producer(Vector sharedQueue, int size) { this.sharedQueue = sharedQueue; this.SIZE = size; } @Override public void run() { // 生产数据 for (int i = 0; i < 7; i++) { System.out.println("Produced:" + i); try { produce(i); } catch (InterruptedException ex) { Logger.getLogger(Producer.class.getName()).log(Level.SEVERE, null, ex); } } } private void produce(int i) throws InterruptedException { // wait if queue is full while (sharedQueue.size() == SIZE) { synchronized (sharedQueue) { System.out.println("Queue is full " + Thread.currentThread().getName() + " is waiting , size: " + sharedQueue.size()); sharedQueue.wait(); } } // producing element and notify consumers synchronized (sharedQueue) { sharedQueue.add(i); sharedQueue.notifyAll(); } } } |
【消费者】
|
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 |
import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger; public class Consumer implements Runnable { private final Vector sharedQueue; private final int SIZE; public Consumer(Vector sharedQueue, int size) { this.sharedQueue = sharedQueue; this.SIZE = size; } @Override public void run() { // 消费数据 while (true) { try { System.out.println("Consumer: " + consume()); Thread.sleep(50); } catch (InterruptedException ex) { Logger.getLogger(Consumer.class.getName()).log(Level.SEVERE, null, ex); } } } private int consume() throws InterruptedException { // wait if queue is empty while (sharedQueue.isEmpty()) { synchronized (sharedQueue) { System.out.println("Queue is empty " + Thread.currentThread().getName() + " is waiting , size: " + sharedQueue.size()); sharedQueue.wait(); } } //otherwise consume element and notify waiting producer synchronized (sharedQueue) { sharedQueue.notifyAll(); return (Integer) sharedQueue.remove(0); } } } |
【测试函数】
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import java.util.Vector; public class ProducerConsumerSolution { public static void main(String[] args) { Vector sharedQueue = new Vector(); int size = 4; Thread prodThread = new Thread(new Producer(sharedQueue, size), "Producer"); Thread consThread = new Thread(new Consumer(sharedQueue, size), "Consumer"); prodThread.start(); consThread.start(); } } |
运行结果:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
Produced:0 Queue is empty Consumer is waiting , size: 0 Produced:1 Consumer: 0 Produced:2 Produced:3 Produced:4 Produced:5 Queue is full Producer is waiting , size: 4 Consumer: 1 Produced:6 Queue is full Producer is waiting , size: 4 Consumer: 2 Consumer: 3 Consumer: 4 Consumer: 5 Consumer: 6 Queue is empty Consumer is waiting , size: 0 |
from:https://www.cnblogs.com/xbq8080/p/10371214.html
View Details