Run 方法可以被同步吗?大家帮我看看为什么这个同步老是有问题
/*
什么时候用同步代码块,什么时候同步函数?使用有什么区别?
*/
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);
}
*/
}
}