首页 > 代码库 > 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 }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。