三线程交替打印指定字符串
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();
}
推荐阅读
- 放屁有这三个特征的,请注意啦!这说明你的身体毒素太多
- 一个人的旅行,三亚
- 2018-02-06第三天|2018-02-06第三天 不能再了,反思到位就差改变
- 第三节|第三节 快乐和幸福(12)
- android第三方框架(五)ButterKnife
- 遇到一哭二闹三打滚的孩子,怎么办┃山伯教育
- 三十年后的广场舞大爷
- 一百二十三夜,请嫁给我
- 2018年9月5日,星期三,天气晴
- 即将到手三百万