请教JAVA高手!关于线程的同步机制synchronized 用法
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的进程。但是不行,不知道哪里出了问题,请高手指教
------解决方案--------------------你这个程序锁的对象不同,一个是对t1加锁,另一个是对t2加锁,所以就不会有同步,我把你的程序改了改,你可以试试:
public class threadDemo extends Thread {
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());
}
}