请教JAVA高手!关于线程的同步机制synchronized 用法

来源:百度知道 编辑:UC知道 时间:2024/05/18 23:11:24
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());
}
}

我想让这个程序

同步代码:synchronized()里传入的不能是this,二需要是某个随意的字符串。
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("ss"){
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);
//System.out.println("active: "+Thread.activeCount());
t1.start();
t2.start();
System.out.println("active: