三线程交替打印指定字符串

public class a200602经典多线程 { static int num = 0; //给定一个字符串双线程交替打印 static class MyThread extends Thread{ privateString str; privateString str2; public MyThread(String str,String str2) { this.str = str; this.str2 = str2; } @Override public voidrun() { synchronized (MyThread.class){ for(; num.length(); ){ System.out.println(str.charAt(num)+str2); num++; MyThread.class.notifyAll(); try{ MyThread.sleep(100); MyThread.class.wait(); }catch (Exception E){ E.printStackTrace(); } } } } }public static void main(String[] args) { String str = "213456789"; MyThread t1 = new MyThread(str,"第一个线程"); MyThread t2 = new MyThread(str,"第二个线程"); MyThread t3 = new MyThread(str,"第三个线程"); t1.start(); t2.start(); t3.start(); } }

若是双线程交替打印,则将run方法中的notifyAll替换成notify。对于特殊的字符串也可以通过写多个thread分别实现。
【三线程交替打印指定字符串】//======================runable
static class Thread3 implements Runnable{ privateString str; public Thread3(String str) { this.str = str; }public void run() { for(char a : str.toCharArray()){ System.out.print(a); }} }public static void main(){ Thread3 ts = new Thread3("str"); new Thread(ts).start(); new Thread(ts).start(); new Thread(ts).start(); }

    推荐阅读