public class Demo1 {
public static void main(String[] args) throws IOException {
//计算结果
long num = 0;
//创建对象
FileOutputStream foss = new FileOutputStream(new File("number.txt"));
//循环1~20的数
for (int i = 1; i < 21; i++) {
//累加每次计算的结果
num = num + count(i);
}
//将long型转换成string型
String str = String.valueOf(num);
//将string转换成char数组
char[] numarr = str.toCharArray();
//遍历数组
for (int i = 0; i < numarr.length; i++) {
//写在文件上
foss.write((int)numarr);
}
//关闭流
foss.close();
}
//创建阶乘方法
public static long count(int c) {
//阶乘结果
long ride = 1;
//遍历每个数
for (int i = c; i > 0; i--) {
//计算阶乘,没一个数逐次减一相乘
ride = ride * i;
}
//返回阶乘数
return ride;
}
}public class Demo2 {
public static void main(String[] args) {
//开启1线程
new mythread("老大").start();
//开启2线程
new mythread("老二").start();
//开启3线程
new mythread("老三").start();
//开启4线程
new mythread("老四").start();
//开启5线程
new mythread("老五").start();
}
}
class mythread extends Thread {
//设置共享变量
private static int packet = 5;
//有参构造方法
public mythread(String name) {
//调用父类设置姓名
super(name);
}
//重写run方法
public void run() {
//创建循环
while (true) {
//同步代码
synchronized (Thread.class) {
//判断抢红包次数
if (packet <= 0) {
//退出循环
break;
}
//异常
try {
//300ms延时
Thread.sleep(300);
//异常
} catch (InterruptedException e) {
e.printStackTrace();
}
//获取范围在1-10元之间,随即钱数
int money = (int)(Math.random()*10+1);
//开抢
System.out.println(getName() + "抢了" + money + "元");
//抢完红包数减一
packet--;
}
}
}
}| 欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) | 黑马程序员IT技术论坛 X3.2 |