public class threadDemo extends Thread {
int flag;
public threadDemo(String name,int f){
super(name);
this.flag=f;
}
public void run(){
char ch;
System.out.println();
System.out.print(getName()+" start: ");
synchronized(this){
if(flag==0){ for(ch='a';ch<='z';ch++)
System.out.print(ch+" ");
} else
if(flag==1){
for(ch='A';ch<='Z';ch++)
System.out.print(ch+" ");
}
System.out.print(getName()+" end!");
}
} public static void main (String[] args) {
threadDemo t1= new threadDemo("线程1",1);
threadDemo t2= new threadDemo("线程2",0);
t1.start();
t2.start();
System.out.println("active: "+t1.activeCount());
}
} 我想让这个程序按同步机制对象t1,t2分别输出字母的大小写。当t1的进程执行完后,在执行t2的进程。但是不行,不知道哪里出了问题,请高手指教
int flag;
public threadDemo(String name,int f){
super(name);
this.flag=f;
}
public void run(){
char ch;
System.out.println();
System.out.print(getName()+" start: ");
synchronized(this){
if(flag==0){ for(ch='a';ch<='z';ch++)
System.out.print(ch+" ");
} else
if(flag==1){
for(ch='A';ch<='Z';ch++)
System.out.print(ch+" ");
}
System.out.print(getName()+" end!");
}
} public static void main (String[] args) {
threadDemo t1= new threadDemo("线程1",1);
threadDemo t2= new threadDemo("线程2",0);
t1.start();
t2.start();
System.out.println("active: "+t1.activeCount());
}
} 我想让这个程序按同步机制对象t1,t2分别输出字母的大小写。当t1的进程执行完后,在执行t2的进程。但是不行,不知道哪里出了问题,请高手指教
int flag;
public static Object lock = new Object(); public threadDemo(String name, int f) {
super(name);
this.flag = f;
} public void run() {
char ch;
synchronized (lock) {
System.out.print(getName() + " start: ");
if (flag == 0) { for (ch = 'a'; ch <= 'z'; ch++)
System.out.print(ch + " ");
} else if (flag == 1) {
for (ch = 'A'; ch <= 'Z'; ch++)
System.out.print(ch + " ");
}
System.out.println(getName() + " end!");
}
} public static void main(String[] args) {
threadDemo t1 = new threadDemo("线程1", 1);
threadDemo t2 = new threadDemo("线程2", 0);
t1.start();
t2.start();
System.out.println("active: " + t1.activeCount());
}
}