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

xueyepiaoling 2007-06-23 05:43:15
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的进程。但是不行,不知道哪里出了问题,请高手指教
...全文
238 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
xueyepiaoling 2007-06-23
  • 打赏
  • 举报
回复
谢谢,明白拉
huoyin 2007-06-23
  • 打赏
  • 举报
回复
同步可以使用this对象,只是用在楼主所举的例子上不合适,如果某个对象的方法不能被两个或多个线程同时访问时,这个时候需要synchronized(this)

也就是说,synchronized哪个对象是要依据你实际的的业务需求。
xueyepiaoling 2007-06-23
  • 打赏
  • 举报
回复
谢谢,我还有个问题,要同步的话是不是不可以用this.是不是必须要创建一个统一的对象,否则是不是还是没有同步?
huoyin 2007-06-23
  • 打赏
  • 举报
回复
你这个程序锁的对象不同,一个是对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());
}
}

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧