public class a200602经典多线程 {
static int num = 0;
//给定一个字符串双线程交替打印
static class MyThread extends Thread{
private String str;
private String str2;
public MyThread(String str,String str2) {
this.str = str;
this.str2 = str2;
}
@Override
public void run() {
synchronized (MyThread.class){
for(;num<str.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{
private String 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();
}
本文介绍了一个使用Java实现的多线程交替打印字符串的方法,通过synchronized关键字和wait、notifyAll方法控制线程间的同步,确保了字符的正确交替输出。同时,展示了如何使用Runnable接口创建线程。
640

被折叠的 条评论
为什么被折叠?



