0
点赞
收藏
分享

微信扫一扫

案例 15:多线程:同时打印数字与字母

Go_Viola 05-12 18:00 阅读 4

class NumberThread extends Thread {

   @Override

   public void run() {

       for (int i = 1; i <= 10; i++) {

           System.out.println("数字: " + i);

           try {

               Thread.sleep(500); // 每500毫秒输出一个数字

           } catch (InterruptedException e) {

               e.printStackTrace();

           }

       }

   }

}


class LetterThread extends Thread {

   @Override

   public void run() {

       for (char c = 'A'; c <= 'J'; c++) {

           System.out.println("字母: " + c);

           try {

               Thread.sleep(500); // 每500毫秒输出一个字母

           } catch (InterruptedException e) {

               e.printStackTrace();

           }

       }

   }

}


public class MultiThreadExample {

   public static void main(String[] args) {

       Thread numThread = new NumberThread();

       Thread letterThread = new LetterThread();


       numThread.start();

       letterThread.start();

   }

}class NumberThread extends Thread { @Override public void run() { for (int i = 1; i <= 10; i++) { System.out.println("数字: " + i); try { Thread.sleep(500); // 每500毫秒输出一个数字 } catch (InterruptedException e) { e.printStackTrace(); } } } }

class LetterThread extends Thread { @Override public void run() { for (char c = 'A'; c <= 'J'; c++) { System.out.println("字母: " + c); try { Thread.sleep(500); // 每500毫秒输出一个字母 } catch (InterruptedException e) { e.printStackTrace(); } } } }

public class MultiThreadExample { public static void main(String[] args) { Thread numThread = new NumberThread(); Thread letterThread = new LetterThread();

numThread.start();
    letterThread.start();
}

}

举报

相关推荐

0 条评论