1.main函数中t1和t2都是ThreadTest1,把一个改成ThreadTest2
2.ThreadTest1的run方法中,obj.notifyAll你写成了this.notifyAll
3.int num = (int)(Math.random()*26+1);
public class Thread4 {
public static void main(String[] args)throws Exception{
//随机产生26个字母的表示方法
//String chars = "abcdefghijklmnopqrstuvwxyz";
// System.out.println(chars.charAt((int)(Math.random()*26)));
ArrayList list = new ArrayList();
for(char c='a';c<='z';c++){
list.add(c);
}
String str = "";
for(int i=0;i<26;i++){
int num = (int)(Math.random()*26+1);
str = str+list.get(num);
}
System.out.println(str);
//------------------------------------
Object obj = new Object();
ThreadTest1 t1 = new ThreadTest1(obj);
ThreadTest2 t2 = new ThreadTest2(obj);
t1.start();
t2.start();
}
}
//线程打印1-52
class ThreadTest1 extends Thread{
private Object obj;
public ThreadTest1(Object obj){
this.obj=obj;
}
public void run(){
synchronized(obj){
for(int i=1;i<53;i++){
System.out.print(i+" ");
if(i%2==0){
//唤醒其他线程
obj.notifyAll();
try{
obj.wait();
}
catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
}
}
//线程打印字母
class ThreadTest2 extends Thread{
private Object obj;
public ThreadTest2(Object obj){
this.obj=obj;
}
public void run(){
synchronized(obj){
for(int i=0;i<26;i++){
System.out.print((char)('A'+i)+"");
//唤醒其它线程
obj.notifyAll();
try{
if(i!=25){
obj.wait();
}
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
} |