Java多线程练习题

使用多线程,模拟龟兔赛跑的场景。

public class RabbitAndTurtle extends Thread {

    public int distance = 100;

    static boolean flag = true;

    public int predistance = 0;

    @Override
    public void run() {
        double ran = Math.random();
        String name = Thread.currentThread().getName();
       while (flag){
           try {
               Thread.sleep(100);
           } catch (InterruptedException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
           }
           if (name.equals("乌龟")) {
               if (Math.random() < 1) {
                   predistance += 1;
                   System.out.println(name + "我跑了:" + predistance + "米");
                   if (predistance == 100) {
                       System.out.println("=================乌龟赢了=================");
                       flag = false;
                       break;
                   }
               }
               try {
                   sleep(100);
               } catch (InterruptedException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
               }
           }
           if (name.equals("兔子")) {
               if (Math.random() < 0.3) {
                   predistance += 2;
                   System.out.println(name + "我跑了:" + predistance + "米");
                   if (predistance == 100) {
                       System.out.println("=================兔子赢了=================");
                       flag = false;
                       break;
                   }
               }
           }
           try {
               sleep(200);
           } catch (InterruptedException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
           }

       }

    }
}
public class Race {

    public static void main(String[] args) {
        Thread rabbit = new RabbitAndTurtle();
        Thread turtle = new RabbitAndTurtle();
        rabbit.setName("兔子");
        turtle.setName("乌龟");
        rabbit.start();
        turtle.start();
    }

}

在这里插入图片描述
参考文章:https://blog.csdn.net/Luciferooorz/article/details/77074285

编写一个有两个线程的程序,第一个线程用来计算2~100000之间的素数的个数,第二个线程用来计算100000~200000之间的素数的个数,最后输出结果。

public class test extends Thread{

    int i,j,x = 0;
    test(int m,int n){
        this.i = m;
        this.j = n;
    }
    public void run(){
        int p,q;
        p=0;q=0;

        for(int m=i;m<=j;m++) {
            for(int h=1;h<=m;h++) {
                q=m%h;
                if(q==0)p=p+1;
            }
            if(p==2) {
                x=x+1;
            }
            p=0;
        }
        System.out.println("输出"+i+"到"+j+"之间的质数个数:"+x);
    }
    public static void main(String[] args) {

        test thread1 =  new test(2,100000);
        test thread2 =  new test(100000,200000);
        thread1.start();
        thread2.start();

    }
}

在这里插入图片描述

使用多线程实现多个文件同步复制功能,并在控制台显示复制的进度,进度以百分比表示。例如:把文件A复制到E盘某文件夹下,在控制台上显示“XXX文件已复制10%”,“XXX文件已复制20%”……“XXX文件已复制100%”,“XXX复制完成!”

public class copyfile extends Thread{

    public File older;// 源文件路径
    public File newer;// 复制目标路径

    public copyfile(String older, String newer) {
        this.older = new File(older);
        this.newer = new File(newer);
    }

    @Override
    public void run() {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream(older);
            fos = new FileOutputStream(newer);

            byte[] b = new byte[1024];// 声明一个字节数组,每次读取的数据存到该字节数组里
            int length = 0;// 返回每次读取的数据长度

            long len = older.length();// 获取源文件的长度

            double temp = 0;

            DecimalFormat df = new DecimalFormat("##%");
            try {
                sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            while ((length = fis.read(b)) != -1) {
                fos.write(b, 0, length);// 把每次读取的内容,输出到目标路径文件中
                temp += length;// 把每次读取的数据长度累加
                double d = temp / len;// 计算出已经读取的长度占文件总长度的比率
                int jd = (int) d;
                if (jd % 10 == 0) {
                    System.out.println(older.getName() + "文件复制了:" + df.format(d));
                }
            }

            System.out.println(older.getName() + "复制完毕!");

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fis.close();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

public class test {

    public static void main(String[] args) {
        copyfile cf1 = new copyfile("E:\\test\\a.CHM", "F:\\test\\a.CHM");
        copyfile cf2 = new copyfile("E:\\test\\b.CHM", "F:\\test\\b.CHM");
        copyfile cf3 = new copyfile("E:\\test\\c.CHM", "F:\\test\\c.CHM");

        cf1.start();
        cf2.start();
        cf3.start();
    }
}

在这里插入图片描述

设计4个线程,其中两个线程每次对j增加1,另外两个线程对j每次减少1。考虑到线程的安全性写出程序。

public class ManyThreads2 {
    private int j = 0;

    public synchronized void inc() {
        j++;
        System.out.println(Thread.currentThread().getName() + "inc" + j);
    }

    public synchronized void dec() {
        j--;
        System.out.println(Thread.currentThread().getName() + "dec" + j);
    }

}

public class MyTest {

    private ManyThreads2 many = new ManyThreads2();

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        MyTest myTest = new MyTest();
        myTest.test();
    }

    public void test() {
        for (int i = 0; i < 2; i++) {
            new Thread(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    for (int i = 0; i < 20; i++) {
                        many.inc();
                    }
                }

            }).start();
            new Thread(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    for (int i = 0; i < 20; i++) {
                        many.dec();
                    }
                }

            }).start();
        }
    }

}

在这里插入图片描述

  • 5
    点赞
  • 43
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值