首页 文章 精选 留言 我的

精选列表

搜索[socket编程],共10000篇文章
优秀的个人博客,低调大师

(牛客腾讯思维编程题)编码编码分组打印下标(java 版本+ C版本)

假定一种编码的编码范围是a ~ y的25个字母,从1位到4位的编码,如果我们把该编码按字典序排序,形成一个数组如下: a, aa, aaa,aaaa, aaab, aaac, … …, b, ba, baa, baaa, baab, baac … …, yyyw, yyyx,yyyy 其中a的Index为0,aa的Index为1,aaa的Index为2,以此类推。 编写一个函数,输入是任意一个编码,输出这个编码对应的Index. 输入描述: 输入一个待编码的字符串,字符串长度小于等于100. 输出描述: 输出这个编码的index 示例1 输入 baca 输出 16331 题目解析点击进入 JAVA import java.util.*; public class Main { public static int number(String str) { int add = str.length()-1;//要考虑到字符串的长度 int mul1 = 1 + 25 + 25*25 + 25*25*25;//从左往右,第一位(进位所需要乘以的数值) int mul2 = 1 + 25 + 25*25;//第二位 int mul3 = 1 + 25;//第三位 int mul4 = 1;//第四位 int[] mul = new int[4];//把上面的四个数放到数组里,以便在下面的循环中使用 mul[0] = mul1; mul[1] = mul2; mul[2] = mul3; mul[3] = mul4; char[] ch = str.toCharArray(); int result = 0; for(int i = 0;i < ch.length;i++) { result += (ch[i] - 'a')*mul[i]; } result += add;//最后把长度考虑进去,不然会出现错误,比如a和aa都会返回0 return result; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String str = scanner.next(); scanner.close(); int result = number(str); System.out.println(result); } } C /* * 五笔编码 * * 五笔的编码范围是a ~ y的25个字母,从1位到4位的编码,如果我们把五笔的编码按字典序排序,形成一个数组如下: * a, aa, aaa, aaaa, aaab, aaac, … …, b, ba, baa, baaa, baab, baac … …, yyyw, yyyx, yyyy * 其中a的Index为0,aa的Index为1,aaa的Index为2,以此类推。 * 编写一个函数,输入是任意一个编码,比如baca,输出这个编码对应的Index; * 编写一个函数,输入是任意一个Index,比如12345,输出这个Index对应的编码。 */ void WubiIndex(const string &input) { const int NUM = 25; const char* p = input.c_str(); int index = 0; int N = 3; int SUM[4] = {1}; for(int i = 1; i < 4; ++i) SUM[i] = NUM * (SUM[i-1]) + 1; while(*p) { int temp = 0; index += (*p -'a')*SUM[N--]; ++p; } cout<<"index is "<<index<<endl; } void WubiCoding(int index) { const int NUM = 25; int SUM[4] = {1}; for(int i = 1; i < 4; ++i) SUM[i] = NUM * (SUM[i-1]) + 1; char ch[5] = {'\0'}; int N = 3; int M = 0; while(index > 0) { ch[M++] = 'a' + (index - 1)/SUM[N]; index = (index - 1)%SUM[N--]; } cout<<"string is "<<ch<<endl; }

优秀的个人博客,低调大师

Java并发编程笔记1-竞争条件&初识原子类&可重入锁

我们知道,在多线程访问一个共享变量的时候会发生安全问题。 首先看下面例子: public class Counter { private int count; public void add(){ try{ for (int i = 0;i<200;i++){ Thread.sleep(100); this.count++; System.out.println(this.count); } }catch (Exception e ){ e.printStackTrace(); } } } public class Test { public static void main(String[] args) { final Counter counter = new Counter(); new Thread(new Runnable() { public void run() { counter.add(); } }).start(); new Thread(new Runnable() { public void run() { counter.add(); } }).start(); new Thread(new Runnable() { public void run() { counter.add(); } }).start(); } } 运行结果如下: 如果没发生线程对数据的赃操作,3个线程执行,结果会累加到600的,看上面结果明显没有,并且出现一下重复的数据。这是因为存在3个线程同时操作同一个数字,导致输出重复数字。 解决办法: 1.在方法上加上synchronized关键字。如下图: 虽然结果不会出现重复,但是synchronized效率及其低下,运行速度明显被拖慢。原因是,for循环中的i变量是每个线程都有独自的局部变量,各不影响,但是每个线程都要排队进入这个方法,排队睡觉,这样就导致效率低下 2.在竞争条件上加synchronized,我们知道各个线程其实竞争的是count这个成员变量。因此在此地方加即可。如下图: 这样运行效率比方法一快了很多,因为省去了排队进入方法,排队睡觉。只需要排队取count值即可,这样效率比方法一快。 注意上图中,输出语句并不是竞争条件,并不一定要放在synchroized里面,这里放在里面是为了让线程取到值自增后立即输出,这样输出就不会发生混论,不发生抢占输出问题,一样能累加到600, 如果把输出放在synchronized外面会出现值有重复现象,因为累加后的值并没有立即输出,这样导致输出混乱,但仍然能加到600.知识输出不安全罢了。 3.使用原子类型,比如将上面的代码的int count类型改成AtomicInteger count类型,我们知道获取count的值然后再自加个1是可能会出现问题的,也就是结果出现重复数字。AtomicInteger类型是以同步的方法解决这个问题的。如下图: 结果如下图: 可以看到数字的输出没有严格的排队,但是数据确实给你保证的了,就是完整的加到600.这也恰恰因为不是严格的进行排队,才是的这种方法比前面两种方法的效率大大改进。 理论总结:synchronized是一种内部锁,就是所对象内部给我们提供的,因为每一个对象有一个状态变量,相当于一个锁,进入同步块,改变这个变量。别的线程进入之后就要判断这个变量有没有改变。 一个线程获取它本生已经持有的锁,这是可以成功的。我们知道多个线程同时抢占同一个锁它们是失败的。因为它们之间是互斥的。但是呢,一个线程再次获取一个自己已经拿过的锁是可以成功的,那么它是能够成功的。 看如下例子: public class Widget { public synchronized void doSth(){ } } public class ChildWidget extends Widget { @Override public synchronized void doSth() { super.doSth(); } } public class Test { public static void main(String[] args) { Widget w = new ChildWidget(); w.doSth(); } } 子类调用自己的方法的那个synchroized那个锁是w对象的这个锁,而在子类方法中的super.doSth()父类中的方法的synchronized的锁也是w对象的锁。因此不要被子类继承父类的方法中的锁所迷惑了。 因此这种方式叫做内部锁的可重入机制,也叫可重入锁。

优秀的个人博客,低调大师

编程大神一道题带你搞定Python函数中形参和实参问题

昨天在Python学习群里有位路人甲问了个Python函数中关于形参和实参一个很基础的问题,虽然很基础,但是对于很多小白来说不一定简单,反而会被搞得稀里糊涂。人生苦短,我用Python。 为了解答大家的这个疑惑,小编在此举个栗子,希望大家能够彻底的理解实参和形参在Python中的用法。 首先,大家一起看个栗子。 不可更改的对象 这个函数的输出值是多少?很多人会回答7,其实程序运行之后,其答案是6,点解呢? 为什么在这里形参的数值并不改变实参的数值? 这里需要给大家普及一个Python中的基础,在python中,string(字符串), tuples(元组), 和number(数值)是不可更改的对象,而list(列表),dict(字典)等则是可以修改的对象。 也就是说,这里形参的数值对于外部的实参的数值(number类型,不可变)来说是没有任何关系的,他们虽然是同一个名字,但是其指向对象是不一样的。所以当在程序最后进行打印a输出值的时候,其输出仍然是6。 下面这个栗子我们来看看可变的对象,以list(列表)作为实验对象。 可更改的对象 这个函数的输出值是多少?很多人会回答[1,2],其实程序运行之后,其答案是[2,1]。 与第一个栗子刚刚相反,这里形参的数值调用把实参改变了。因为本例中参数传递的是列表,其是可更改的对象,在函数内部经过系列赋值变化之后,所以在程序运行之后其输出值产生了变化。 山重水复疑无路,柳暗花明又一村。这道题经常会被招聘公司和企业拿去作为面试题,考察面试狗的Python基础知识,希望大家好好参详,日后碰到类似的问题加以注意,少走弯路! 最后感谢在Python群中积极提问的好学者,然我们大家一起为学好Python而奋斗吧!

优秀的个人博客,低调大师

【读书笔记《Android游戏编程之从零开始》】16.游戏开发基础(动画)

1. Animation动画 在Android 中,系统提供了动画类 Animation ,其中又分为四种动画效果: ● AlphaAnimation:透明度渐变动画 ●ScaleAnimation:渐变尺寸缩放动画; ● TranslateAnimation:移动动画 ● RotateAnimation:旋转动画 这4种动画效果的创建方法如下: (1) AlphaAnimation 透明度渐变动画 Animation alphaA = new AlphaAnimation(float fromAlpha,float toAlpha) 第一个参数:动画开始时的透明度 第二个参数:动画结束时的透明度 两个参数的取值范围为[0,1],从完全透明到完全不透明。 (2)ScaleAnimation 渐变尺寸缩放动画 Animation scaleA = new ScaleAnimation(float fromX,float toX,float fromY,float toY,int pivotXType,float pivotXValue,int pivoteYType,float pivoteYValue) 第一个参数:动画起始时X坐标上的伸缩比例 第二个参数:动画结束时X坐标上的伸缩比例 第三个参数:动画起始时Y坐标上的伸缩比例 第四个参数:动画结束时Y坐标上的伸缩比例 第五个参数:动画在X轴相对于物体的位置类型 第六个参数:动画相对于物体X坐标的位置 第七个参数:动画在Y轴相对于物体的位置类型 第八个参数:动画相对于物体Y坐标的位置 其中位置类型分为以下三种: Animation.ABSOLUTE:相对位置是屏幕左上角,绝对位置; Animation.RELATIVE_TO_SELF:相对位置是自身 View, 取值为 0 时,表示相对于是自身左上角,取值为1是相对于自身的右下角; Animation.RELATIVE_TO_PAREND:相对父类 View 的位置。 (3)TranslateAnimation 移动动画 Animation translateA = new TranslateAnimation(float fromXDelta,float toXDelta,float fromYDelta,float YDelta) 第一个参数:动画起始时X轴上的位置 第二个参数:动画结束时X轴上的位置 第三个参数:动画起始时Y轴上的位置 第四个参数:动画结束时Y轴上的位置 (4)RotateAnimation 旋转动画 Animation rotateA = new RotateAnimation(float fromDegrees,float toDegrees,int pivotXType,float pivotXValue,int pivotYType,float pivotYValue) 第一个参数:动画起始时旋转角度 第二个参数:动画旋转到的角度 第三个参数:动画在X轴相对于物件位置类型 第四个参数:动画相对于物件的X坐标的开始位置 第五个参数:动画在Y轴相对于物体的位置类型 第六个参数:动画相对于物体的Y坐标的位置 不管哪一种动画,都有一些通用方法,比如: restart():重新播放动画; setDuration(int time):设置动画播放时间,单位是毫秒。 下面是实例演示,效果如下: 新建项目,游戏框架为 View 游戏框架, 具体步骤参照“10.游戏开发基础(View 游戏框架)”。 修改 MyView类,代码如下: MyView 记住,Animation的每种动画都是对整个画布进行操作。 2.自定义动画 (1)动态位图 在之前随笔中,曾在屏幕上让文本字符串跟随玩家手指移动,从而行程一个动态的效果;那么让一张位图形成动态效果也很容易,只要不断改变位图的X或者Y轴的坐标即可。下面利用一张位图形成海的波浪效果。 新建项目,游戏框架为SurfaceView 框架,准备图片water.png如下: 修改MySurfaceView类,代码如下: MySurfaceView (2)帧动画 前面是利用改变位图的X或者Y坐标行程动画效果。当然在游戏开发中,很多动态的帧数不仅仅只有一帧,而所谓帧动画,其实就是一帧一帧按照一定的顺序进行播放实现的。下面是实例演示,效果如下: 新建项目,游戏框架为 SurfaceView 框架,在项目中导入下面6张png图片: 修改MySurfaceView类,代码如下: MySurfaceView (3)剪切图动画 剪切图动画类似于帧动画的形式,唯一的区别就是动态帧全部放在了一张图片中,然后通过设置可视区域完成。简单的解释,绘图时通过控制X轴或者Y轴坐标,来逐帧显示要显示的图片部分,达到动态的效果。下面是实例,运行效果和前面的帧动画一样。步骤如下: 新建项目,游戏框架为 SurfaceView 框架,在项目中导入下面这张png图片: 修改MySurfaceView类,代码如下: package com.example.ex4_11; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.view.SurfaceHolder; import android.view.SurfaceHolder.Callback; import android.view.SurfaceView; public class MySurfaceView extends SurfaceView implements Callback, Runnable { // 用于控制SurfaceView 的大小、格式等,并且主要用于监听SurfaceView 的状态 private SurfaceHolder sfh; // 声明一个画布 private Canvas canvas; // 声明一个线程 private Thread th; // 线程消亡的标识符 private boolean flag; private Paint paint; // 创建位图 private Bitmap bmp = BitmapFactory.decodeResource(this.getResources(), R.drawable.wifi_all); // 记录当前播放帧 private int currentFrame; public MySurfaceView(Context context) { super(context); // 实例SurfaceView sfh = this.getHolder(); // 为SurfaceView添加状态监听 sfh.addCallback(this); paint = new Paint(); // 画笔无锯齿 paint.setAntiAlias(true); } /** * SurfaceView 视图创建,响应此函数 */ @Override public void surfaceCreated(SurfaceHolder holder) { flag = true; // 实例线程 th = new Thread(this); // 启动线程 th.start(); } /** * SurfaceView 视图状态发生改变时,响应此函数 */ @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } /** * SurfaceView 视图消亡时,响应此函数 */ @Override public void surfaceDestroyed(SurfaceHolder holder) { flag = false; } private int minW = bmp.getWidth() / 6; private void myDraw() { try { //居中点X轴坐标 int cW = this.getWidth() / 2 - minW / 2; //居中点Y轴坐标 int cH = this.getHeight() / 2 - bmp.getHeight() / 2; canvas = sfh.lockCanvas(); if (canvas != null) { // 刷屏,画布白色 canvas.drawColor(Color.WHITE); canvas.save(); // 设置画布的可视区域,大小为每帧的大小,居中 canvas.clipRect(cW, cH, cW + minW, cH + bmp.getHeight()); // 绘制位图,居中 canvas.drawBitmap(bmp, cW - currentFrame * minW, cH, paint); canvas.restore(); } } catch (Exception e) { // TODO: handle exception } finally { if (canvas != null) { sfh.unlockCanvasAndPost(canvas); } } } /** * 游戏逻辑 */ private void logic() { currentFrame++; // 当播放的当前帧大于并且等于帧数组时,重置当前帧为0 if (currentFrame >= 6) { currentFrame = 0; } } @Override public void run() { while (flag) { long start = System.currentTimeMillis(); myDraw(); logic(); long end = System.currentTimeMillis(); try { if (end - start < 500) { Thread.sleep(500 - (end - start)); } } catch (Exception e) { e.printStackTrace(); } } } } 本文转自秋楓博客园博客,原文链接:http://www.cnblogs.com/yc-755909659/p/4171732.html,如需转载请自行联系原作者

优秀的个人博客,低调大师

Spark RDD/Core 编程 API入门系列 之rdd案例(map、filter、flatMap、groupByKey、reduceB...

声明: 大数据中,最重要的算子操作是:join !!! 典型的transformation和action val nums = sc.parallelize(1 to 10) //根据集合创建RDD map适用于 package com.zhouls.spark.cores import org.apache.spark.{SparkConf, SparkContext} /** * Created by Administrator on 2016/9/27. */ object Transformations { def main(args: Array[String]) { val conf = new SparkConf().setAppName("Transformations").setMaster("local") val sc = new SparkContext(conf) val nums = sc.parallelize(1 to 10) //根据集合创建RDD val mapped = nums.map(item => 2 + item) mapped.collect.foreach(println) } }map源码 /** * Return a new RDD by applying a function to all elements of this RDD. */ def map[U: ClassTag](f: T => U): RDD[U] = withScope { val cleanF = sc.clean(f) new MapPartitionsRDD[U, T](this, (context, pid, iter) => iter.map(cleanF)) } filter适用于 package com.zhouls.spark.cores import org.apache.spark.{SparkConf, SparkContext} /** * Created by Administrator on 2016/9/27. */ object Transformations { def main(args: Array[String]) { val conf = new SparkConf().setAppName("Transformations").setMaster("local") val sc = new SparkContext(conf) val nums = sc.parallelize(1 to 10) //根据集合创建RDD val mapped = nums.map(item => 2 + item) val filtered = nums.filter(item => item%2 == 0) filtered.collect.foreach(println) } } filter源码 /** * Return a new RDD containing only the elements that satisfy a predicate. */ def filter(f: T => Boolean): RDD[T] = withScope { val cleanF = sc.clean(f) new MapPartitionsRDD[T, T]( this, (context, pid, iter) => iter.filter(cleanF), preservesPartitioning = true) } flatMap适用于 package com.zhouls.spark.cores import org.apache.spark.{SparkConf, SparkContext} /** * Created by Administrator on 2016/9/27. */ object Transformations { def main(args: Array[String]) { val conf = new SparkConf().setAppName("Transformations").setMaster("local") val sc = new SparkContext(conf) val nums = sc.parallelize(1 to 10) //根据集合创建RDD val mapped = nums.map(item => 2 + item) // mapped.collect.foreach(println) val filtered = nums.filter(item => item%2 == 0) // filtered.collect.foreach(println) val bigData = Array("Scala Spark","Java Hadoop","Java Tachyon") val bigDataString = sc.parallelize(bigData) val words = bigDataString.flatMap(line => line.split(" ")) words.collect.foreach(println) sc.stop() } } flatMap源码 /** * Return a new RDD by first applying a function to all elements of this * RDD, and then flattening the results. */ def flatMap[U: ClassTag](f: T => TraversableOnce[U]): RDD[U] = withScope { val cleanF = sc.clean(f) new MapPartitionsRDD[U, T](this, (context, pid, iter) => iter.flatMap(cleanF)) } 成为大牛,必写的写法 -> groupByKey适用于 package com.zhouls.spark.cores import org.apache.spark.{SparkConf, SparkContext} /** * Created by Administrator on 2016/9/27. */ object Transformations { def main(args: Array[String]) { val sc = sparkContext("Transformations Operations") //创建SparkContext // mapTransformation(sc)//map案例 // filterTransformation(sc)//filter案例 // flatMapTransformation(sc)//flatMap案例 groupByKeyTransformation(sc) sc.stop() //停止sparkContext,释放相关的Driver对象,释放资源 } def sparkContext(name:String)={ val conf = new SparkConf().setAppName("Transformations").setMaster("local") val sc = new SparkContext(conf) sc } def mapTransformation(sc:SparkContext){ val nums = sc.parallelize(1 to 10) //根据集合创建RDD val mapped = nums.map(item => 2 * item) //map适用于任何类型的元素且对其作用的集合中的每一个元素循环遍历并调用其作为参数的函数对每一个遍历的元素进行具体化处理 mapped.collect.foreach(println)//收集计算结果并通过foreach循环打印 } def filterTransformation(sc:SparkContext){ val nums = sc.parallelize(1 to 20) //根据集合创建RDD val filtered = nums.filter(item => item%2 == 0)//根据filter中作为参数的函数Boolean来判断符合条件的元素,并基于这些元素构成新的MapPartitionsRDD。 filtered.collect.foreach(println)//收集计算结果并通过foreach循环打印 } def flatMapTransformation(sc:SparkContext){ val bigData = Array("Scala Spark","Java Hadoop","Java Tachyon")//实例化字符串类型的Array val bigDataString = sc.parallelize(bigData)//创建以字符串为元素类型的MapPartitionsRDD val words = bigDataString.flatMap(line => line.split(" "))//首先是通过传入的作为参数的函数来作用于RDD的每个字符串进行单词切分(是以集合的方式存在的),然后把切分后的结果合并成一个大的集合,是{Scala Spark Java Hadoop Java Tachyon} words.collect.foreach(println)//收集计算结果并通过foreach循环打印 } def groupByKeyTransformation(sc:SparkContext){ val data = Array(Tuple2(100,"Spark"),Tuple2(100,"Tachyon"),Tuple2(70,"Hadoop"),Tuple2(80,"Kafka"),Tuple2(80,"HBase")) val dataRDD = sc.parallelize(data) val grouped = dataRDD.groupByKey() grouped.collect.foreach(println)//收集计算结果并通过foreach循环打印 } } groupByKey源码 ** * Group the values for each key in the RDD into a single sequence. Allows controlling the * partitioning of the resulting key-value pair RDD by passing a Partitioner. * The ordering of elements within each group is not guaranteed, and may even differ * each time the resulting RDD is evaluated. * * Note: This operation may be very expensive. If you are grouping in order to perform an * aggregation (such as a sum or average) over each key, using [[PairRDDFunctions.aggregateByKey]] * or [[PairRDDFunctions.reduceByKey]] will provide much better performance. * * Note: As currently implemented, groupByKey must be able to hold all the key-value pairs for any * key in memory. If a key has too many values, it can result in an [[OutOfMemoryError]]. */ def groupByKey(partitioner: Partitioner): RDD[(K, Iterable[V])] = self.withScope { // groupByKey shouldn't use map side combine because map side combine does not // reduce the amount of data shuffled and requires all map side data be inserted // into a hash table, leading to more objects in the old gen. val createCombiner = (v: V) => CompactBuffer(v) val mergeValue = (buf: CompactBuffer[V], v: V) => buf += v val mergeCombiners = (c1: CompactBuffer[V], c2: CompactBuffer[V]) => c1 ++= c2 val bufs = combineByKey[CompactBuffer[V]]( createCombiner, mergeValue, mergeCombiners, partitioner, mapSideCombine = false) bufs.asInstanceOf[RDD[(K, Iterable[V])]] } /** * Group the values for each key in the RDD into a single sequence. Hash-partitions the * resulting RDD with into `numPartitions` partitions. The ordering of elements within * each group is not guaranteed, and may even differ each time the resulting RDD is evaluated. * * Note: This operation may be very expensive. If you are grouping in order to perform an * aggregation (such as a sum or average) over each key, using [[PairRDDFunctions.aggregateByKey]] * or [[PairRDDFunctions.reduceByKey]] will provide much better performance. * * Note: As currently implemented, groupByKey must be able to hold all the key-value pairs for any * key in memory. If a key has too many values, it can result in an [[OutOfMemoryError]]. */ def groupByKey(numPartitions: Int): RDD[(K, Iterable[V])] = self.withScope { groupByKey(new HashPartitioner(numPartitions)) } reduceByKey适用于 package com.zhouls.spark.cores import org.apache.spark.{SparkConf, SparkContext} /** * Created by Administrator on 2016/9/27. */ object Transformations { def main(args: Array[String]) { val sc = sparkContext("Transformations Operations") //创建SparkContext // mapTransformation(sc)//map案例 // filterTransformation(sc)//filter案例 // flatMapTransformation(sc)//flatMap案例 // groupByKeyTransformation(sc)//groupByKey案例 reduceByKeyTransformation(sc)//reduceByKey案例 sc.stop() //停止sparkContext,释放相关的Driver对象,释放资源 } def sparkContext(name:String)={ val conf = new SparkConf().setAppName("Transformations").setMaster("local") val sc = new SparkContext(conf) sc } def mapTransformation(sc:SparkContext){ val nums = sc.parallelize(1 to 10) //根据集合创建RDD val mapped = nums.map(item => 2 * item) //map适用于任何类型的元素且对其作用的集合中的每一个元素循环遍历并调用其作为参数的函数对每一个遍历的元素进行具体化处理 mapped.collect.foreach(println)//收集计算结果并通过foreach循环打印 } def filterTransformation(sc:SparkContext){ val nums = sc.parallelize(1 to 20) //根据集合创建RDD val filtered = nums.filter(item => item%2 == 0)//根据filter中作为参数的函数Boolean来判断符合条件的元素,并基于这些元素构成新的MapPartitionsRDD。 filtered.collect.foreach(println)//收集计算结果并通过foreach循环打印 } def flatMapTransformation(sc:SparkContext){ val bigData = Array("Scala Spark","Java Hadoop","Java Tachyon")//实例化字符串类型的Array val bigDataString = sc.parallelize(bigData)//创建以字符串为元素类型的MapPartitionsRDD val words = bigDataString.flatMap(line => line.split(" "))//首先是通过传入的作为参数的函数来作用于RDD的每个字符串进行单词切分(是以集合的方式存在的),然后把切分后的结果合并成一个大的集合,是{Scala Spark Java Hadoop Java Tachyon} words.collect.foreach(println)//收集计算结果并通过foreach循环打印 } def groupByKeyTransformation(sc:SparkContext){ val data = Array(Tuple2(100,"Spark"),Tuple2(100,"Tachyon"),Tuple2(70,"Hadoop"),Tuple2(80,"Kafka"),Tuple2(80,"HBase"))//准备数据 val dataRDD = sc.parallelize(data)//根据集合创建RDD val grouped = dataRDD.groupByKey()//按照相同的key对value进行分组,分组后的value是一个集合 grouped.collect.foreach(println)//收集计算结果并通过foreach循环打印 } def reduceByKeyTransformation(sc:SparkContext){ val lines = sc.textFile("D://SoftWare//spark-1.6.2-bin-hadoop2.6//README.md") val words = lines.flatMap{ line => line.split(" ")} val pairs = words.map { word => (word,1) } val wordCountsOdered = pairs.reduceByKey(_+_)//对相同的key,进行value的累计(包括local和reducer级别同时reduce) wordCountsOdered.collect.foreach(wordNumberPair => println(wordNumberPair._1 + ":" + wordNumberPair._2))//收集计算结果并通过foreach循环打印 } } reduceByKey源码 /** * Merge the values for each key using an associative reduce function. This will also perform * the merging locally on each mapper before sending results to a reducer, similarly to a * "combiner" in MapReduce. Output will be hash-partitioned with the existing partitioner/ * parallelism level. */ def reduceByKey(func: (V, V) => V): RDD[(K, V)] = self.withScope { reduceByKey(defaultPartitioner(self), func) } join适用于 package com.zhouls.spark.cores import org.apache.spark.{SparkConf, SparkContext} /** * Created by Administrator on 2016/9/27. */ object Transformations { def main(args: Array[String]) { val sc = sparkContext("Transformations Operations") //创建SparkContext // mapTransformation(sc)//map案例 // filterTransformation(sc)//filter案例 // flatMapTransformation(sc)//flatMap案例 // groupByKeyTransformation(sc)//groupByKey案例 // reduceByKeyTransformation(sc)//reduceByKey案例 joinTransformation(sc)//join案例 sc.stop() //停止sparkContext,释放相关的Driver对象,释放资源 } def sparkContext(name:String)={ val conf = new SparkConf().setAppName("Transformations").setMaster("local") val sc = new SparkContext(conf) sc } def mapTransformation(sc:SparkContext){ val nums = sc.parallelize(1 to 10) //根据集合创建RDD val mapped = nums.map(item => 2 * item) //map适用于任何类型的元素且对其作用的集合中的每一个元素循环遍历并调用其作为参数的函数对每一个遍历的元素进行具体化处理 mapped.collect.foreach(println)//收集计算结果并通过foreach循环打印 } def filterTransformation(sc:SparkContext){ val nums = sc.parallelize(1 to 20) //根据集合创建RDD val filtered = nums.filter(item => item%2 == 0)//根据filter中作为参数的函数Boolean来判断符合条件的元素,并基于这些元素构成新的MapPartitionsRDD。 filtered.collect.foreach(println)//收集计算结果并通过foreach循环打印 } def flatMapTransformation(sc:SparkContext){ val bigData = Array("Scala Spark","Java Hadoop","Java Tachyon")//实例化字符串类型的Array val bigDataString = sc.parallelize(bigData)//创建以字符串为元素类型的MapPartitionsRDD val words = bigDataString.flatMap(line => line.split(" "))//首先是通过传入的作为参数的函数来作用于RDD的每个字符串进行单词切分(是以集合的方式存在的),然后把切分后的结果合并成一个大的集合,是{Scala Spark Java Hadoop Java Tachyon} words.collect.foreach(println)//收集计算结果并通过foreach循环打印 } def groupByKeyTransformation(sc:SparkContext){ val data = Array(Tuple2(100,"Spark"),Tuple2(100,"Tachyon"),Tuple2(70,"Hadoop"),Tuple2(80,"Kafka"),Tuple2(80,"HBase"))//准备数据 val dataRDD = sc.parallelize(data)//根据集合创建RDD val grouped = dataRDD.groupByKey()//按照相同的key对value进行分组,分组后的value是一个集合 grouped.collect.foreach(println)//收集计算结果并通过foreach循环打印 } def reduceByKeyTransformation(sc:SparkContext){ val lines = sc.textFile("D://SoftWare//spark-1.6.2-bin-hadoop2.6//README.md") val words = lines.flatMap{ line => line.split(" ")} val pairs = words.map { word => (word,1) } val wordCountsOdered = pairs.reduceByKey(_+_)//对相同的key,进行value的累计(包括local和reducer级别同时reduce) wordCountsOdered.collect.foreach(wordNumberPair => println(wordNumberPair._1 + ":" + wordNumberPair._2))//收集计算结果并通过foreach循环打印 } def joinTransformation(sc:SparkContext){ val studentNames = Array(Tuple2(1,"Spark"),Tuple2(2,"Tachyon"),Tuple2(3,"Hadoop")) val studentScores = Array(Tuple2(1,100),Tuple2(2,95),Tuple2(3,65)) val names = sc.parallelize(studentNames) val scores = sc.parallelize(studentScores) val studentNamesAndScores = names.join(scores) studentNamesAndScores.collect.foreach(println)//收集计算结果并通过foreach循环打印 } } join源码 /** * Cartesian join with another [[DataFrame]]. * * Note that cartesian joins are very expensive without an extra filter that can be pushed down. * * @param right Right side of the join operation. * @group dfops * @since 1.3.0 */ def join(right: DataFrame): DataFrame = { Join(logicalPlan, right.logicalPlan, joinType = Inner, None) } /** * Inner equi-join with another [[DataFrame]] using the given column. * * Different from other join functions, the join column will only appear once in the output, * i.e. similar to SQL's `JOIN USING` syntax. * * {{{ * // Joining df1 and df2 using the column "user_id" * df1.join(df2, "user_id") * }}} * * Note that if you perform a self-join using this function without aliasing the input * [[DataFrame]]s, you will NOT be able to reference any columns after the join, since * there is no way to disambiguate which side of the join you would like to reference. * * @param right Right side of the join operation. * @param usingColumn Name of the column to join on. This column must exist on both sides. * @group dfops * @since 1.4.0 */ def join(right: DataFrame, usingColumn: String): DataFrame = { join(right, Seq(usingColumn)) } /** * Inner equi-join with another [[DataFrame]] using the given columns. * * Different from other join functions, the join columns will only appear once in the output, * i.e. similar to SQL's `JOIN USING` syntax. * * {{{ * // Joining df1 and df2 using the columns "user_id" and "user_name" * df1.join(df2, Seq("user_id", "user_name")) * }}} * * Note that if you perform a self-join using this function without aliasing the input * [[DataFrame]]s, you will NOT be able to reference any columns after the join, since * there is no way to disambiguate which side of the join you would like to reference. * * @param right Right side of the join operation. * @param usingColumns Names of the columns to join on. This columns must exist on both sides. * @group dfops * @since 1.4.0 */ def join(right: DataFrame, usingColumns: Seq[String]): DataFrame = { // Analyze the self join. The assumption is that the analyzer will disambiguate left vs right // by creating a new instance for one of the branch. val joined = sqlContext.executePlan( Join(logicalPlan, right.logicalPlan, joinType = Inner, None)).analyzed.asInstanceOf[Join] // Project only one of the join columns. val joinedCols = usingColumns.map(col => joined.right.resolve(col)) val condition = usingColumns.map { col => catalyst.expressions.EqualTo(joined.left.resolve(col), joined.right.resolve(col)) }.reduceLeftOption[catalyst.expressions.BinaryExpression] { (cond, eqTo) => catalyst.expressions.And(cond, eqTo) } Project( joined.output.filterNot(joinedCols.contains(_)), Join( joined.left, joined.right, joinType = Inner, condition) ) } /** * Inner join with another [[DataFrame]], using the given join expression. * * {{{ * // The following two are equivalent: * df1.join(df2, $"df1Key" === $"df2Key") * df1.join(df2).where($"df1Key" === $"df2Key") * }}} * @group dfops * @since 1.3.0 */ def join(right: DataFrame, joinExprs: Column): DataFrame = join(right, joinExprs, "inner") /** * Join with another [[DataFrame]], using the given join expression. The following performs * a full outer join between `df1` and `df2`. * * {{{ * // Scala: * import org.apache.spark.sql.functions._ * df1.join(df2, $"df1Key" === $"df2Key", "outer") * * // Java: * import static org.apache.spark.sql.functions.*; * df1.join(df2, col("df1Key").equalTo(col("df2Key")), "outer"); * }}} * * @param right Right side of the join. * @param joinExprs Join expression. * @param joinType One of: `inner`, `outer`, `left_outer`, `right_outer`, `leftsemi`. * @group dfops * @since 1.3.0 */ def join(right: DataFrame, joinExprs: Column, joinType: String): DataFrame = { // Note that in this function, we introduce a hack in the case of self-join to automatically // resolve ambiguous join conditions into ones that might make sense [SPARK-6231]. // Consider this case: df.join(df, df("key") === df("key")) // Since df("key") === df("key") is a trivially true condition, this actually becomes a // cartesian join. However, most likely users expect to perform a self join using "key". // With that assumption, this hack turns the trivially true condition into equality on join // keys that are resolved to both sides. // Trigger analysis so in the case of self-join, the analyzer will clone the plan. // After the cloning, left and right side will have distinct expression ids. val plan = Join(logicalPlan, right.logicalPlan, JoinType(joinType), Some(joinExprs.expr)) .queryExecution.analyzed.asInstanceOf[Join] // If auto self join alias is disabled, return the plan. if (!sqlContext.conf.dataFrameSelfJoinAutoResolveAmbiguity) { return plan } // If left/right have no output set intersection, return the plan. val lanalyzed = this.logicalPlan.queryExecution.analyzed val ranalyzed = right.logicalPlan.queryExecution.analyzed if (lanalyzed.outputSet.intersect(ranalyzed.outputSet).isEmpty) { return plan } // Otherwise, find the trivially true predicates and automatically resolves them to both sides. // By the time we get here, since we have already run analysis, all attributes should've been // resolved and become AttributeReference. val cond = plan.condition.map { _.transform { case catalyst.expressions.EqualTo(a: AttributeReference, b: AttributeReference) if a.sameRef(b) => catalyst.expressions.EqualTo(plan.left.resolve(a.name), plan.right.resolve(b.name)) }} plan.copy(condition = cond) } cogroup的scala版,适用于 package com.zhouls.spark.cores import org.apache.spark.{SparkConf, SparkContext} /** * Created by Administrator on 2016/9/27. */ object Transformations { def main(args: Array[String]) { val sc = sparkContext("Transformations Operations") //创建SparkContext // mapTransformation(sc)//map案例 // filterTransformation(sc)//filter案例 // flatMapTransformation(sc)//flatMap案例 // groupByKeyTransformation(sc)//groupByKey案例 // reduceByKeyTransformation(sc)//reduceByKey案例 // joinTransformation(sc)//join案例 cogroupTransformation(sc)//cogroup案例 sc.stop() //停止sparkContext,释放相关的Driver对象,释放资源 } def sparkContext(name:String)={ val conf = new SparkConf().setAppName("Transformations").setMaster("local") val sc = new SparkContext(conf) sc } def mapTransformation(sc:SparkContext){ val nums = sc.parallelize(1 to 10) //根据集合创建RDD val mapped = nums.map(item => 2 * item) //map适用于任何类型的元素且对其作用的集合中的每一个元素循环遍历并调用其作为参数的函数对每一个遍历的元素进行具体化处理 mapped.collect.foreach(println)//收集计算结果并通过foreach循环打印 } def filterTransformation(sc:SparkContext){ val nums = sc.parallelize(1 to 20) //根据集合创建RDD val filtered = nums.filter(item => item%2 == 0)//根据filter中作为参数的函数Boolean来判断符合条件的元素,并基于这些元素构成新的MapPartitionsRDD。 filtered.collect.foreach(println)//收集计算结果并通过foreach循环打印 } def flatMapTransformation(sc:SparkContext){ val bigData = Array("Scala Spark","Java Hadoop","Java Tachyon")//实例化字符串类型的Array val bigDataString = sc.parallelize(bigData)//创建以字符串为元素类型的MapPartitionsRDD val words = bigDataString.flatMap(line => line.split(" "))//首先是通过传入的作为参数的函数来作用于RDD的每个字符串进行单词切分(是以集合的方式存在的),然后把切分后的结果合并成一个大的集合,是{Scala Spark Java Hadoop Java Tachyon} words.collect.foreach(println)//收集计算结果并通过foreach循环打印 } def groupByKeyTransformation(sc:SparkContext){ val data = Array(Tuple2(100,"Spark"),Tuple2(100,"Tachyon"),Tuple2(70,"Hadoop"),Tuple2(80,"Kafka"),Tuple2(80,"HBase"))//准备数据 val dataRDD = sc.parallelize(data)//根据集合创建RDD val grouped = dataRDD.groupByKey()//按照相同的key对value进行分组,分组后的value是一个集合 grouped.collect.foreach(println)//收集计算结果并通过foreach循环打印 } def reduceByKeyTransformation(sc:SparkContext){ val lines = sc.textFile("D://SoftWare//spark-1.6.2-bin-hadoop2.6//README.md") val words = lines.flatMap{ line => line.split(" ")} val pairs = words.map { word => (word,1) } val wordCountsOdered = pairs.reduceByKey(_+_)//对相同的key,进行value的累计(包括local和reducer级别同时reduce) wordCountsOdered.collect.foreach(wordNumberPair => println(wordNumberPair._1 + ":" + wordNumberPair._2))//收集计算结果并通过foreach循环打印 } def joinTransformation(sc:SparkContext){ val studentNames = Array(Tuple2(1,"Spark"),Tuple2(2,"Tachyon"),Tuple2(3,"Hadoop")) val studentScores = Array(Tuple2(1,100),Tuple2(2,95),Tuple2(3,65)) val names = sc.parallelize(studentNames) val scores = sc.parallelize(studentScores) val studentNamesAndScores = names.join(scores) studentNamesAndScores.collect.foreach(println)//收集计算结果并通过foreach循环打印 } def cogroupTransformation(sc:SparkContext){ val namesLists = Array(Tuple2(1,"xiaoming"),Tuple2(2,"xiaozhou"),Tuple2(3,"xiaoliu")) val scoresLists = Array(Tuple2(1,100),Tuple2(2,95),Tuple2(3,85),Tuple2(1,75),Tuple2(2,65),Tuple2(3,55)) val names = sc.parallelize(namesLists) val scores = sc.parallelize(scoresLists) val namesListsAndScores = names.cogroup(scores) namesListsAndScores.collect.foreach(println)//收集计算结果并通过foreach循环打印 } } cogroup源码 /** * For each key k in `this` or `other1` or `other2` or `other3`, * return a resulting RDD that contains a tuple with the list of values * for that key in `this`, `other1`, `other2` and `other3`. */ def cogroup[W1, W2, W3](other1: RDD[(K, W1)], other2: RDD[(K, W2)], other3: RDD[(K, W3)], partitioner: Partitioner) : RDD[(K, (Iterable[V], Iterable[W1], Iterable[W2], Iterable[W3]))] = self.withScope { if (partitioner.isInstanceOf[HashPartitioner] && keyClass.isArray) { throw new SparkException("Default partitioner cannot partition array keys.") } val cg = new CoGroupedRDD[K](Seq(self, other1, other2, other3), partitioner) cg.mapValues { case Array(vs, w1s, w2s, w3s) => (vs.asInstanceOf[Iterable[V]], w1s.asInstanceOf[Iterable[W1]], w2s.asInstanceOf[Iterable[W2]], w3s.asInstanceOf[Iterable[W3]]) } } /** * For each key k in `this` or `other`, return a resulting RDD that contains a tuple with the * list of values for that key in `this` as well as `other`. */ def cogroup[W](other: RDD[(K, W)], partitioner: Partitioner) : RDD[(K, (Iterable[V], Iterable[W]))] = self.withScope { if (partitioner.isInstanceOf[HashPartitioner] && keyClass.isArray) { throw new SparkException("Default partitioner cannot partition array keys.") } val cg = new CoGroupedRDD[K](Seq(self, other), partitioner) cg.mapValues { case Array(vs, w1s) => (vs.asInstanceOf[Iterable[V]], w1s.asInstanceOf[Iterable[W]]) } } /** * For each key k in `this` or `other1` or `other2`, return a resulting RDD that contains a * tuple with the list of values for that key in `this`, `other1` and `other2`. */ def cogroup[W1, W2](other1: RDD[(K, W1)], other2: RDD[(K, W2)], partitioner: Partitioner) : RDD[(K, (Iterable[V], Iterable[W1], Iterable[W2]))] = self.withScope { if (partitioner.isInstanceOf[HashPartitioner] && keyClass.isArray) { throw new SparkException("Default partitioner cannot partition array keys.") } val cg = new CoGroupedRDD[K](Seq(self, other1, other2), partitioner) cg.mapValues { case Array(vs, w1s, w2s) => (vs.asInstanceOf[Iterable[V]], w1s.asInstanceOf[Iterable[W1]], w2s.asInstanceOf[Iterable[W2]]) } } /** * For each key k in `this` or `other1` or `other2` or `other3`, * return a resulting RDD that contains a tuple with the list of values * for that key in `this`, `other1`, `other2` and `other3`. */ def cogroup[W1, W2, W3](other1: RDD[(K, W1)], other2: RDD[(K, W2)], other3: RDD[(K, W3)]) : RDD[(K, (Iterable[V], Iterable[W1], Iterable[W2], Iterable[W3]))] = self.withScope { cogroup(other1, other2, other3, defaultPartitioner(self, other1, other2, other3)) } /** * For each key k in `this` or `other`, return a resulting RDD that contains a tuple with the * list of values for that key in `this` as well as `other`. */ def cogroup[W](other: RDD[(K, W)]): RDD[(K, (Iterable[V], Iterable[W]))] = self.withScope { cogroup(other, defaultPartitioner(self, other)) } /** * For each key k in `this` or `other1` or `other2`, return a resulting RDD that contains a * tuple with the list of values for that key in `this`, `other1` and `other2`. */ def cogroup[W1, W2](other1: RDD[(K, W1)], other2: RDD[(K, W2)]) : RDD[(K, (Iterable[V], Iterable[W1], Iterable[W2]))] = self.withScope { cogroup(other1, other2, defaultPartitioner(self, other1, other2)) } /** * For each key k in `this` or `other`, return a resulting RDD that contains a tuple with the * list of values for that key in `this` as well as `other`. */ def cogroup[W]( other: RDD[(K, W)], numPartitions: Int): RDD[(K, (Iterable[V], Iterable[W]))] = self.withScope { cogroup(other, new HashPartitioner(numPartitions)) } /** * For each key k in `this` or `other1` or `other2`, return a resulting RDD that contains a * tuple with the list of values for that key in `this`, `other1` and `other2`. */ def cogroup[W1, W2](other1: RDD[(K, W1)], other2: RDD[(K, W2)], numPartitions: Int) : RDD[(K, (Iterable[V], Iterable[W1], Iterable[W2]))] = self.withScope { cogroup(other1, other2, new HashPartitioner(numPartitions)) } /** * For each key k in `this` or `other1` or `other2` or `other3`, * return a resulting RDD that contains a tuple with the list of values * for that key in `this`, `other1`, `other2` and `other3`. */ def cogroup[W1, W2, W3](other1: RDD[(K, W1)], other2: RDD[(K, W2)], other3: RDD[(K, W3)], numPartitions: Int) : RDD[(K, (Iterable[V], Iterable[W1], Iterable[W2], Iterable[W3]))] = self.withScope { cogroup(other1, other2, other3, new HashPartitioner(numPartitions)) } 本文转自大数据躺过的坑博客园博客,原文链接:http://www.cnblogs.com/zlslch/p/5913846.html,如需转载请自行联系原作者

优秀的个人博客,低调大师

Android Day05-网络编程之文件下载之多线程断点续传技术

文件下载之多线程断点续传技术底层实现 通过HttpURLConnection连接 断点续传核心步骤: 1.UI设计 2.获取服务器文件的大小,通过连接的一个方法getContentLength()来得到。 3.在客户端创建一个和将要下载的文件的同样大小的同名文件。 4.计算每个线程的起始位置和结束位置 5.开启多个线程,采用RandomAccessFile类,根据计算得到的起始位置和结束位置来随机的读取服务 器资源的输出流,并且实时的采用RandomAccessFile类保存线程读取到的字节位置。 6.判断线程结束和文件上传成功。 断点续传具体实现: 1.UI设计 下载主界面设计 进度条单独存放在一个布局文件中,注意进度条要采用以下的样式的进度条。 2.代码逻辑 多线程断点续传的技术可以说是目前学Android课程以来最难、代码最长的一个案例,那么如何 有章有序的将代码写出来呢? 思路整理: 1)网络访问权限和SD卡访问权限的添加 2)初始化动作及下载点击事件的书写 3)随机读取文件线程类的定义 具体代码: 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 //注册点击事件 public void click(Viewv){ path=et_path.getText().toString().trim(); Stringthreadcount_str=et_threadcount.getText().toString().trim(); final int threadcount=Integer.parseInt(threadcount_str); if (TextUtils.isEmpty(path)||threadcount< 0 ){ Toast.makeText(getApplicationContext(), "输入错误" , 0 ).show(); return ; } list_pbBars= new ArrayList<ProgressBar>(); //先清空进度条布局 ll_layout.removeAllViews(); //添加进度条 for ( int i= 0 ;i<threadcount;i++){ //得到进度条的View对象 Viewitem_pb_View=View.inflate(getApplicationContext(),R.layout.item_progress, null ); //通过View再得到进度条 ProgressBarpb_bar=(ProgressBar)item_pb_View.findViewById(R.id.item_pb); list_pbBars.add(pb_bar); ll_layout.addView(item_pb_View); } try { //将服务器文件路径用File包装一下,以便获得它的文件名。 sourceFile= new File(path); //访问URL得到文件的大小,通过Content-Length得到。 new Thread(){ public void run() { System.out.println( "xxx" +Thread.currentThread().getName()); try { //创建HttpURLConnection URLurl= new URL(path); HttpURLConnectionconn=(HttpURLConnection)url.openConnection(); conn.setRequestMethod( "GET" ); //获取状态码 int responseCode=conn.getResponseCode(); if (responseCode== 200 ) { //获取资源文件的长度 sourceFileLength=conn.getContentLength(); sourceFileName=sourceFile.getName(); clientFile= new RandomAccessFile(Environment.getExternalStorageDirectory()+ "/" +sourceFileName, "rw" ); clientFile.setLength(sourceFileLength); //正在运行的线程 runningThreadCount=threadcount; //第3步:计算每个线程读取文件的起始和结束位置 int blockSize=sourceFileLength/threadcount; for ( int i= 0 ;i<threadcount;i++){ //得到每个线程读取的起始和结束位置 int start_index=i*blockSize; int end_index=(i+ 1 )*blockSize- 1 ; int last_index=- 1 ; if (i==threadcount- 1 ) { end_index=sourceFileLength- 1 ; } //------如果采用了断点续传,线程的起始位置就是上次记录位置。 FilerecordIndexFile= new File(Environment.getExternalStorageDirectory().getPath()+ "/" +i+ ".txt" ); //如果有断点文件,就得到上次记录的读取位置。 if (recordIndexFile.exists()&&recordIndexFile.length()> 0 ) { BufferedReaderbufr= new BufferedReader( new FileReader(recordIndexFile)); last_index=Integer.parseInt(bufr.readLine()); // last_index++; bufr.close(); } else //否则上次读取位置就是开始位置。 { last_index=start_index; } //设置进度条的总长度 list_pbBars.get(i).setMax(( int )(end_index-start_index)); System.out.println( "线程" +i+ "::" +last_index+ "----" +end_index); //第4步:启动线程 new DownloadThread(i,start_index,end_index,last_index).start(); } } else { showToast( "请求不到资源" ); return ; } } catch (Exceptione){ e.printStackTrace(); } } }.start(); //第5步:判断线程结束 } catch (Exceptione){ e.printStackTrace(); } } //定义下载的线程类 class DownloadThread extends Thread{ private int threadID; private int start_index,end_index,last_index; private int total= 0 ; //记录已经读写的总的字节数 public DownloadThread( int threadID, int start_index, int end_index, int last_index){ this .threadID=threadID; this .start_index=start_index; this .end_index=end_index; this .last_index=last_index; this .setName( "线程" +threadID); } public void run(){ try { //创建HttpURLConnection URLurl= new URL(path); HttpURLConnectionconn=(HttpURLConnection)url.openConnection(); conn.setRequestMethod( "GET" ); // conn.setReadTimeout(5); //设置一个头信息Range,表示要读取的流的字节范围。 conn.setRequestProperty( "Range" , "bytes=" +last_index+ "-" +end_index); //获取状态码 int responseCode=conn.getResponseCode(); //注意多线程下载状态得用206来判断 if (responseCode== 206 ) { //得到服务器的输出流 InputStreamserverIn=conn.getInputStream(); //得到客户端的文件输出流 RandomAccessFilemyClientFile= new RandomAccessFile( Environment.getExternalStorageDirectory()+ "/" +sourceFileName, "rwd" ); myClientFile.seek(last_index); //读取服务器文件写入到客户端文件中 //断点续传文件 int len= 0 ; byte []buf= new byte [ 1024 * 1024 ]; while ((len=serverIn.read(buf))!=- 1 ) { myClientFile.write(buf, 0 ,len); total+=len; //实时存储当前读取到的文件位置。 int current_index=last_index+total; //因为此处实时的存储读取文件的位置,将缓冲区buf稍微弄大点。 //改 /***注意读取文件位置的流一定要用RandomAccessFile,因为它可以直接同步到缓存(磁盘上)。***/ RandomAccessFileraffAccessFile= new RandomAccessFile(Environment.getExternalStorageDirectory().getPath()+ "/" +threadID+ ".txt" , "rwd" ); raffAccessFile.write(String.valueOf(current_index).getBytes()); raffAccessFile.close(); //设置进度条的当前进度 list_pbBars.get(threadID).setProgress(( int )(total+last_index-start_index)); } myClientFile.close(); serverIn.close(); //操作共享资源,注意加锁。 synchronized (DownloadThread. class ){ runningThreadCount--; if (runningThreadCount== 0 ) { Toast.makeText(getApplicationContext(), "文件下载完毕" , 0 ).show(); } } } else { showToast( "服务器忙" ); } } catch (Exceptione){ e.printStackTrace(); } } } 本文转自屠夫章哥 51CTO博客,原文链接:http://blog.51cto.com/4259297/1676571,如需转载请自行联系原作者

资源下载

更多资源
Mario

Mario

马里奥是站在游戏界顶峰的超人气多面角色。马里奥靠吃蘑菇成长,特征是大鼻子、头戴帽子、身穿背带裤,还留着胡子。与他的双胞胎兄弟路易基一起,长年担任任天堂的招牌角色。

腾讯云软件源

腾讯云软件源

为解决软件依赖安装时官方源访问速度慢的问题,腾讯云为一些软件搭建了缓存服务。您可以通过使用腾讯云软件源站来提升依赖包的安装速度。为了方便用户自由搭建服务架构,目前腾讯云软件源站支持公网访问和内网访问。

Nacos

Nacos

Nacos /nɑ:kəʊs/ 是 Dynamic Naming and Configuration Service 的首字母简称,一个易于构建 AI Agent 应用的动态服务发现、配置管理和AI智能体管理平台。Nacos 致力于帮助您发现、配置和管理微服务及AI智能体应用。Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据、流量管理。Nacos 帮助您更敏捷和容易地构建、交付和管理微服务平台。

Spring

Spring

Spring框架(Spring Framework)是由Rod Johnson于2002年提出的开源Java企业级应用框架,旨在通过使用JavaBean替代传统EJB实现方式降低企业级编程开发的复杂性。该框架基于简单性、可测试性和松耦合性设计理念,提供核心容器、应用上下文、数据访问集成等模块,支持整合Hibernate、Struts等第三方框架,其适用范围不仅限于服务器端开发,绝大多数Java应用均可从中受益。

用户登录
用户注册
修改密码
忘记密码