Java多線程入門(一)——在屏幕上交替打印數字、字母

題目

編寫一個程序,創建三個任務以及三個運行這些任務的線程:

  1. 第一個任務打印字母a100次
  2. 第二個任務打印字母b100次
  3. 第三個任務打印1~100的整數

如果運行這個程序,則三個線程將共享CPU,並且在控制檯上輪流打印字母和數字。
(因爲現在電腦的CPU都太快了,100個數和字母根本看不出來CPU在交替執行線程,所以我將數字定爲10000

效果

在這裏插入圖片描述

代碼

package P1;

public class thread1 {


    public static void main(String[] args){
        //創建三個任務
        Runnable printA=new PrintChar('a',100);
        Runnable printB=new PrintChar('b',100);
        Runnable print100=new PrintNum(100000);

        //創建線程
        Thread thread3=new Thread(print100);
        Thread thread1=new Thread(printA);
        Thread thread2=new Thread(printB);
        //開始線程
        thread1.start();
        thread2.start();
        thread3.start();
    }
}
class PrintChar implements Runnable{

    private char charToPrint;//需要打印的字母
    private  int times;//需要打印的次數

    public PrintChar() {

    }

    public PrintChar(char charToPrint, int times) {
        this.charToPrint = charToPrint;
        this.times = times;
    }

    @Override
    public void run() {
        for (int i = 0; i <= times; i++) {
            System.out.println(charToPrint);
        }
    }
}

class PrintNum implements Runnable{
    private int lastNum;

    public PrintNum(int lastNum) {
        this.lastNum = lastNum;
    }

    @Override
    public void run() {
        for (int i = 0; i < lastNum; i++) {
            System.out.println(" " + i);
        }
    }
}

思路

該程序創建了三個任務。爲了同時運行它們,創建了三個線程。調用start()方法啓動第一個線程,那麼其中的run()方法就會被執行。當run()方法執行完畢之後,線程就終止了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章