Run 方法可以被同步吗?大家帮我看看为什么这个同步老是有问题

Winyaz 2016-05-20 04:11:42
/*
什么时候用同步代码块,什么时候同步函数?使用有什么区别?
*/

class StopThread {
boolean flag=false;
int n=100;
int m=0;
}
class First implements Runnable{
private StopThread st;
First(StopThread st){
this.st=st;
}
public synchronized void run(){
while(st.n>0){
if(st.flag){
try{
this.wait();
}
catch(InterruptedException e){
System.out.println(Thread.currentThread().getName()+"....Exception...");
}
}
System.out.println(Thread.currentThread().getName()+"....First...");
System.out.println(st.n--);
st.flag=true;
this.notify();
}

}
}
class Second implements Runnable{
private StopThread st;
Second(StopThread st){
this.st=st;
}
public synchronized void run(){
while(st.m<100){
if(!st.flag){
try{
this.wait();
}
catch(InterruptedException e){
System.out.println(Thread.currentThread().getName()+"....Exception...");
}
}
System.out.println(Thread.currentThread().getName()+"....Second...");
System.out.println(st.m++);
st.flag=false;
this.notify();
}
}
}

public class Aboutwait_notify{
public static void main(String args[]){
StopThread st=new StopThread();
First first=new First(st);
Second second=new Second(st);
Thread t1=new Thread(first);
Thread t2=new Thread(second);

t1.start();
t2.start();

int num=0;
/*
while(true){
if(num++==6000){
t1.interrupt();
t2.interrupt();
//st.changeFlag();
break;
}
System.out.println(Thread.currentThread().getName()+"......"+num);
}
*/
}
}
...全文
133 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
rickylin86 2016-05-20
  • 打赏
  • 举报
回复
你对线程First/Second中的run方法采用同步没用啊.因为你这样的同步是针对于线程该对象的同步,所以不同的两个线程是不会达到同步效果的. 不过是同步代码块还是同步函数.要记得一定,线程间的同步是基于同一个对象来同步的.所以主要是用弄清楚线程间同步的这个对象即可.相同则能同步,对象不同就无法达到同步的效果.

62,626

社区成员

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

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