多線程練習題


1.使用多線程,模擬龜兔賽跑的場景。

     按照以往的故事經驗,正確的故事邏輯順序當然是因為兔子不把烏龜放在眼里,松懈了最終輸了比賽。我的設定也是如此,假定烏龜每秒跑五米(是有點快但為了線程的運行速度來看還是寫快點)兔子的速度為每秒十米。但是兔子在跑到一半休息了一點五秒。

        代碼如下:

          

package com.company;

public class ThreadTest1 implements Runnable{
        public void run(){

                try {
                    for(int i = 1;i<=100;i= i+5){
                    System.out.println("烏龜跑了"+i+"米");
                    Thread.sleep(1000);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
}
package com.company;

public class ThreadTest2 implements Runnable{
    public void run(){
        try {
            for(int j = 1;j<=100;j=j+10){
                System.out.println("兔子跑了"+j+"米");
                Thread.sleep(1000);
                if(j==51){
                    Thread.sleep(15000);
                }
            }

        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}
package com.company;

import javax.naming.Name;

public class ThreadMain  {
    static int a = 200;
    public static void main(String[] args) {
      ThreadTest1 threadTest1 = new ThreadTest1();
        ThreadTest2 threadTest2 = new ThreadTest2();
        Thread thread1 = new Thread(threadTest1);
        Thread thread2 = new Thread(threadTest2);
        thread1.start();
        thread2.start();

    }
}

運行結果如下:

 

2、編寫一個有兩個線程的程序,第一個線程用來計算2~100000之間的素數的個數,第二個線程用來計算100000~200000之間的素數的個數,最后輸出結果。

          思路:確定一個數為素數,他只能將本身和1整除,即聲明一個變量,寫兩個循壞嵌套,外面的循壞寫數的范圍,里面的循壞寫除數,每當數能將它的除數整除,變量加1,如果最后變量的值為2即確定此數為素數

              

package com.company;

public class ThreadTest1 implements Runnable{
        public void run(){

                 for(int i=2;i<=100000;i++){
                     int a = 0;
                     for(int j=1;j<=i;j++){
                         if(i%j==0){
                             a++;
                         }
                     }
                     if(a==2)//素數只能整除1和它本身,所以a=2時說明該數為素數
                         System.out.println("線程1========"+i);
                 }
            }
}
package com.company;

public class ThreadTest2 implements Runnable{
    public void run(){
        for(int k=100000;k<=200000;k++){
            int b = 0;
            for(int l=1;l<=k;l++){
                if(k%l==0){
                    b++;
                }
            }
            if(b==2)//素數只能整除1和它本身,所以a=2時說明該數為素數
                System.out.println("線程2======"+k);
        }

    }
}
package com.company;

import javax.naming.Name;

public class ThreadMain  {
    static int a = 200;
    public static void main(String[] args) {
      ThreadTest1 threadTest1 = new ThreadTest1();
        ThreadTest2 threadTest2 = new ThreadTest2();
        Thread thread1 = new Thread(threadTest1);
        Thread thread2 = new Thread(threadTest2);
        thread1.start();
        thread2.start();

    }
}

結果片段:

 

3、使用多線程實現多個文件同步復制功能,並在控制台顯示復制的進度,進度以百分比表示。例如:把文件A復制到E盤某文件夾下,在控制台上顯示“XXX文件已復制10%”,“XXX文件已復制20%”……“XXX文件已復制100%”,“XXX復制完成!”

       代碼如下,設置每次截取代碼長度除以文件總長度得到文件復制百分比,使用“DecimalFormat”類中的format方法將得到的數字乘以100並顯示為百分數。

 1 package com.company;
 2 
 3 import java.io.*;
 4 import java.text.DecimalFormat;
 5 
 6 public class CopyFile extends Thread {
 7 
 8     public File oldFile;
 9     public File newFile;
10 
11     public CopyFile(String oldFile,String newFile) {
12         this.oldFile = new File(oldFile);
13         this.newFile = new File(newFile);
14     }
15 
16     @Override
17     public void run() {
18         FileOutputStream fileOutputStream = null;
19         FileInputStream fileInputStream =null;
20         try {
21             fileOutputStream =  new FileOutputStream(newFile);
22             fileInputStream = new FileInputStream(oldFile);
23             byte[] b = new byte[1024];
24             int length = 0;//返回每次讀取的數據長度
25             long l = oldFile.length();//文件的長度
26             double temp = 0;//
27             DecimalFormat decimalFormat = new DecimalFormat("%");
28             while ((length = fileInputStream.read(b))!=-1){
29                  fileOutputStream.write(b,0,length);
30                  temp += length;//將每次讀到的數據進行累加
31                  double  d = temp/l;
32                  int dd = (int) d;
33                  if(dd%10==0){
34                      System.out.println("文件已經復制"+decimalFormat.format(d));
35                  }
36             }
37             System.out.println(oldFile.getName()+"復制完成");
38         } catch (IOException e) {
39             e.printStackTrace();
40         }finally {
41             try {
42                 fileInputStream.close();
43                 fileOutputStream.close();
44             } catch (IOException e) {
45                 e.printStackTrace();
46             }
47         }
48 
49     }
50 }
package com.company;

public class CopyTest {

    public static void main(String[] args) {
        CopyFile cf1 = new CopyFile("E:\\a.txt", "D:\\a.txt");
        CopyFile cf2 = new CopyFile("E:\\b.txt", "D:\\b.txt");
        CopyFile cf3 = new CopyFile("E:\\c.txt", "D:\\c.txt");

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

    }

}

結果:

 

 


4、設計4個線程,其中兩個線程每次對j增加1,另外兩個線程對j每次減少1。考慮到線程的安全性寫出程序。

        分別書寫四個線程對靜態變量j進行更改,在每個線程中都加入synchronized (ThreadTest.class)保證線程安全,在更改未做完其他線程無法運行

         代碼如下

            

package com.company;

public class ThreadTest1 implements Runnable {
    public void run() {

                try {
                    for (int i = 0; i < 10000; i++) {
                    synchronized (ThreadTest.class) {
                        ThreadTest2.j++;
                        System.out.println("線程1====="+ThreadTest2.j);
                    Thread.sleep(100);
                    }}
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

    }
package com.company;

public class ThreadTest2 implements Runnable{
    public static int j=500;
    public static int k;
    public void run(){

                try {
                    for(int i=0;i<10000;i++){
                    synchronized (ThreadTest.class){
                        j++;
                        System.out.println("線程2====="+j);
                    Thread.sleep(100);
                    }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
package com.company;

public class ThreadTest3 implements Runnable {
    public void run() {

                try {
                    for (int i = 0; i < 10000; i++) {
                    synchronized (ThreadTest.class) {
                        ThreadTest2.j--;
                        System.out.println("線程3=====" + ThreadTest2.j);
                        Thread.sleep(100);
                    }}
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
}
package com.company;

public class ThreadTest4 implements  Runnable {
    public void run() {

                try {
                    for (int i = 0; i < 10000; i++) {
                        synchronized (ThreadTest.class) {
                            ThreadTest2.j--;
                            System.out.println("線程4=====" + ThreadTest2.j);
                            Thread.sleep(100);
                        }}
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
}
package com.company;

import javax.naming.Name;

public class ThreadMain  {
    static int a = 200;
    public static void main(String[] args) {
      ThreadTest1 threadTest1 = new ThreadTest1();
        ThreadTest2 threadTest2 = new ThreadTest2();
        ThreadTest3 threadTest3 = new ThreadTest3();
        ThreadTest4 threadTest4 = new ThreadTest4();
        Thread thread1 = new Thread(threadTest1);
        Thread thread2 = new Thread(threadTest2);
        Thread thread3 = new Thread(threadTest3);
        Thread thread4 = new Thread(threadTest4);
        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();

    }
}

截取部分結果如下:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM