多线程学习笔记
一年一度的校园招聘马上要来开序幕,为了把自己卖个好价钱,这几天也开始做历年的Java笔试题目。很多的Java基础没有看过,下面也是边学边做,废话也不多说,直接上题目。
-
题目
多线程。对于字符串“北京公交越来越便捷”用多线实现每秒打出一个字(换行)。如下
北
北京
北京公
北京公交
. . . . . .
-
分析
本题的要求是要用多线程来进行打印,每秒打出一个字,这就涉及到线程安全的问题。当线程T要打印时,T首先要明确要打印哪几个字,打印完以后要告诉其他的线程,“我是线程T,我已经打印了前n个字,你们应该打印前n+1个字”,其他的线程收到通知后开始打印。具体实现如下:
-
代码
1 public class MultiThread implements Runnable{ 2 private String str = "北京公交越来越便捷"; 3 private int count = str.length(); 4 private int num = 1; 5 private String str1; 6 7 public void run(){ 8 while(true){ 9 synchronized(this){ 10 if(num <= count){ 11 str1 = str.substring(0, num); 12 System.out.print(Thread.currentThread().getName()+"->"); 13 for(int i=0; i<num; i++){ 14 System.out.print(str1.substring(i, i+1)); 15 try { 16 Thread.sleep(1000); 17 } catch (InterruptedException e) { 18 e.printStackTrace(); 19 } 20 } 21 System.out.println(); 22 }else{ 23 break; 24 } 25 26 num++; 27 } 28 } 29 } 30 31 public static void main(String[] args) { 32 MultiThread mul1 = new MultiThread(); 33 Thread t1 = new Thread(mul1,"t1"); 34 Thread t2 = new Thread(mul1,"t2"); 35 Thread t3 = new Thread(mul1,"t3"); 36 Thread t4 = new Thread(mul1,"t4"); 37 Thread t5 = new Thread(mul1,"t5"); 38 Thread t6 = new Thread(mul1,"t6"); 39 Thread t7 = new Thread(mul1,"t7"); 40 Thread t8 = new Thread(mul1,"t8"); 41 t1.start(); 42 t2.start(); 43 t3.start(); 44 t4.start(); 45 t5.start(); 46 t6.start(); 47 t7.start(); 48 t8.start(); 49 } 50 }
-
运行结果