1、2、4代码如下:
package com.text;
import java.util.Random;
class arrayInput implements Runnable{
private int []a=new int[1000];
int i;
int randomNum;
Random ran=new Random();
public void run() {
while(true){
synchronized (this) { //在这里同步一下,2个线程都会进入while循环,当第一个线程执行一次后就会释放资源解开锁,
if(i%3==0){ //每输入3个数到数组里都停顿1秒
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
if(i==1000) { //当输入到1000时结束循环
break;
}
int randomNum=ran.nextInt(1000); //不知道你往数组输入什么数据就往里输入0到1000的随机数了。
a[i]=randomNum;
System.out.println(Thread.currentThread().getName()+"a["+i+"]="+a[i]); //打印输入的数组数据看效果
i++;
}
}
}
}
public class arrayDemo {
public static void main(String[] args) {
arrayInput a=new arrayInput();
Thread t1=new Thread(a,"线程1:");
Thread t2=new Thread(a,"线程2:");
t1.start();
t2.start();
}
}
2
package com.text;
class MyThread implements Runnable{
private String ThreadName;
int t1,t2,t3,t4,t5; //定义5个线程的计数器,分别计算5个线程执行了多少次
public MyThread(){
System.out.println("创建线程4");
}
public void run(){
while(true){
if(t1==6||t2==6||t3==6||t4==6||t5==6)
break;
ThreadName=Thread.currentThread().getName();
switch(ThreadName){
case "线程1":{t1++;System.out.println(ThreadName+"...."+"计数:"+t1);break;}
case "线程2":{t2++;System.out.println(ThreadName+"...."+"计数:"+t2);break;}
case "线程3":{t3++;System.out.println(ThreadName+"...."+"计数:"+t3);break;}
case "线程4":{t4++;System.out.println(ThreadName+"...."+"计数:"+t4);break;}
case "线程5":{t5++;System.out.println(ThreadName+"...."+"计数:"+t5);break;}
}
}
}
}
public class threadDemo {
public static void main(String[] args) {
MyThread myt=new MyThread();
Thread t[]=null;
for(int i=1;i<=5;i++){
new Thread(myt,"线程"+i).start(); //创建5个线程,线程名分别为线程1、线程2、线程3、线程4、线程5,
//这里使用匿名对象但是我希望在循环中用数组存5个线程循结束,一下直接启动5个线程这样效率高点,你试试
}
}
}
4
package com.text;
import java.math.BigInteger;
class zero{
zero(){
int count=0;
int[] res = new int[3000]; //知道结果是2000多位定义一个3000位的数组存放结果
final int limit = 1000; //阶乘从1000开始
res[1] = 1;
int max_now = 1;
for(int step = 1; step <= limit;step++)
{
int temp = 0;
int now = max_now; //40320
int zero;
for(zero = 1; zero <=now;zero++) //PASS掉末尾的零.
{
if(res[zero] != 0)
break;
}
for(int carry = zero-1;carry <= now;carry++)
{
res[carry] *= step;
res[carry] += temp;
temp = 0;
if(res[carry] >= 10)
{
int carry_temp = carry;
temp = res[carry];
if(carry_temp <= max_now)
{
res[carry_temp] = temp%10;
temp/=10;
carry_temp++;
}
if(carry_temp > max_now)
{
while(temp >= 10)
{
res[carry_temp] = temp%10;
temp /= 10;
carry_temp++;
}
res[carry_temp] = temp;
temp = 0;
max_now = carry_temp;
}
}
}
}
System.out.println("结果是"+max_now+"位");
for(int j = max_now; j > 0; j--)
{ if(res[j]==0){
count++; //计算出有多少个0
}
System.out.print(res[j]);
}
System.out.print("\n");
System.out.print("一共有"+count+"个0");
}
}
public class zeroDemo {
public static void main(String[] args) {
zero z=new zero();
}
}
|