首页 > 代码库 > Thread类

Thread类

 1 public class PrintChar implements Runnable {
 2     private char charToPrint;
 3     private int times;
 4 
 5     public PrintChar(char c, int t) {
 6         charToPrint = c;
 7         times = t;
 8     }
 9 
10     public void run() {
11         try {
12             for (int i = 0; i < times; i++) {
13                 System.out.print(charToPrint);
14                 Thread.sleep(1); // 休眠
15                 Thread.yield(); // 让出线程
16             }
17         } catch (InterruptedException e) {
18 
19             e.printStackTrace();
20         }
21     }
22 }
 1 public class PrintNum implements Runnable{
 2     
 3     private int lastNum;
 4     public PrintNum(int n){
 5         lastNum = n;
 6     }
 7     public void run() {
 8         for(int i = 1; i <= lastNum; i++){
 9             System.out.print(i);
10         }
11     }
12 }
 1 public class Ch2Sample1 {
 2 
 3     public static void main(String[] args) {
 4         Runnable printA = new PrintChar(‘a‘, 100);
 5         Runnable printB = new PrintChar(‘b‘, 100);
 6         Runnable printn = new PrintNum(100);
 7         
 8         Thread t1 = new Thread(printA);
 9         Thread t2 = new Thread(printB);
10         Thread t3 = new Thread(printn);
11         
12         t1.start();
13         t2.start();
14         t3.start();
15      }
16 }