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的进程。但是不行,不知道哪里出了问题,请高手指教

解决方案 »

  1.   

    你这个程序锁的对象不同,一个是对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());
    }
    }
      

  2.   

    谢谢,我还有个问题,要同步的话是不是不可以用this.是不是必须要创建一个统一的对象,否则是不是还是没有同步?
      

  3.   

    同步可以使用this对象,只是用在楼主所举的例子上不合适,如果某个对象的方法不能被两个或多个线程同时访问时,这个时候需要synchronized(this)也就是说,synchronized哪个对象是要依据你实际的的业务需求。