黑马程序员技术交流社区
标题:
写十个线程,第一个线程求1到10的和,
[打印本页]
作者:
Ethan丶
时间:
2015-9-26 21:34
标题:
写十个线程,第一个线程求1到10的和,
写十个线程,第一个线程求1到10的和,
* 第二个11到20的和,第三个求21到30的和...第10个求91到100的和,求十个线程的和
作者:
冰霜之卅
时间:
2015-9-26 23:58
class adds implements Runnable{
int s;
int sum=0;
adds(int s){
this.s=s;
}
public void run(){
for(int i=0;i<10;i++){
sum=(sum+s);
s++;
}
System.out.println(sum);
}
}
public class SumThread {
public static void main(String[]args) throws InterruptedException{
adds s1=new adds(1);
adds s2=new adds(11);
adds s3=new adds(21);
adds s4=new adds(31);
adds s5=new adds(41);
adds s6=new adds(51);
adds s7=new adds(61);
adds s8=new adds(71);
adds s9=new adds(81);
adds s0=new adds(91);
Thread thread1=new Thread(s1);
Thread thread2=new Thread(s2);
Thread thread3=new Thread(s3);
Thread thread4=new Thread(s4);
Thread thread5=new Thread(s5);
Thread thread6=new Thread(s6);
Thread thread7=new Thread(s7);
Thread thread8=new Thread(s8);
Thread thread9=new Thread(s9);
Thread thread0=new Thread(s0);
thread1.start();
thread2.start();
thread3.start();
thread4.start();
thread5.start();
thread6.start();
thread7.start();
thread8.start();
thread9.start();
thread0.start();
thread0.join();
thread9.join();
thread7.join();
thread6.join();
int avg=(s1.sum+s2.sum+s3.sum+s4.sum+s5.sum+s6.sum+s7.sum+s8.sum+s9.sum+s0.sum);
System.out.println(avg);
}
}
想用for循环创建多线程 怎么弄都不行 不知道如何使用循环创建多线程。。。
虽然代码很傻 但是也勉强满足需求了。
求大神 优化代码。
作者:
Ethan丶
时间:
2015-9-27 00:13
package heimaexam;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeMap;
/*
* "adsadasdsdsdxz",获取字符串中每一个字母出现的次数:a(2)b(1)...
*/
public class TreeMapTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// 定义已个字符串
System.out.println("请输入字符串:");
String line = sc.nextLine();
// 定义一个TreeMap
TreeMap<Character, Integer> tm = new TreeMap<Character, Integer>();
// 字符串转换为字符数组
char[] ch = line.toCharArray();
// 遍历
for (char chr : ch) {
Integer i = tm.get(chr);
// 如果null;该键值不存在,把该字符作为键,1作为值存储
if (i == null) {
tm.put(chr, 1);
} else {
// 不是null;该键值存在,值加1,重写存储该键和值
i++;
tm.put(chr, i);
}
}
// 定义字符串缓冲区变量
StringBuilder sb = new StringBuilder();
// 遍历,得到键、值,进行按照要求拼接
Set<Character> set = tm.keySet();
for (Character key : set) {
Integer value = tm.get(key);
sb.append(key).append("(").append(value).append(")");
}
//把字符串缓冲区转换为字符串输出
System.out.println(sb.toString());
}
}
复制代码
作者:
Ethan丶
时间:
2015-9-27 00:14
Ethan丶 发表于 2015-9-27 00:13
请输入字符串:
asdxzcxzvwer
a(1)c(1)d(1)e(1)r(1)s(1)v(1)w(1)x(2)z(2)
作者:
jekyll
时间:
2015-9-27 00:43
午夜大神多啊,我都懒得敲。。。
向刻苦的同学学习
作者:
Ethan丶
时间:
2015-9-28 20:45
创建十个进程?数组加循环创建线程?
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2