Java 线程间通信
我有两个线程运行t1和t2。当t2通知t1时,t2应立即进入等待状态。但是,这是不可能的,因为一旦它通知t1,它应该完成当前进程,并且只有在当前线程执行结束后,t1执行才会开始。但是我想在t2通知之后立即启动t1,这样我就可以将t2置于等待状态,以便t1在while循环中通知。这在同步块中是可能的吗?。我尝试了以下不起作用的代码。我还对编码行进行了注释,以提及我希望的编码方式Java 线程间通信,java,multithreading,Java,Multithreading,我有两个线程运行t1和t2。当t2通知t1时,t2应立即进入等待状态。但是,这是不可能的,因为一旦它通知t1,它应该完成当前进程,并且只有在当前线程执行结束后,t1执行才会开始。但是我想在t2通知之后立即启动t1,这样我就可以将t2置于等待状态,以便t1在while循环中通知。这在同步块中是可能的吗?。我尝试了以下不起作用的代码。我还对编码行进行了注释,以提及我希望的编码方式 public void passNo(int data)//thread t1 {
public void passNo(int data)//thread t1
{
this.data1=data;
synchronized(thread2)
{
System.out.println("thread1 running");
data1=data1+100;
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("thread1 going to notify thread two");
thread2.notify();
/* try {
thread1.wait();
} catch (Exception e) {
e.printStackTrace();
}*/
}//sync
try {
Thread.sleep(1000);
} catch (Exception e) {}
System.out.println("im done, receiver go");
//}
}
public void ramos(int data)//thread t2
{
synchronized(thread1)
{
try{
System.out.println("I am thread 2 waiting for thread 1");
thread1.wait();//Problem-not notified ever by sender
System.out.println("Notified by sender thread");}
catch(InterruptedException ex){}
System.out.println("I am released");
n=obj.getInteger();
setInteger();
System.out.println("Notified");
}//sync
j++;
//}//while
}
class ClaObj
{
public static void main(String[] args)
{
Sender s=new Sender();
Receiver r=new Receiver();
r.classobj(s);
Thread thread1 = new Thread(s);
Thread thread2 = new Thread(r);
s.sendthrobj(thread1);
r.recvthobj(thread1);
thread1.start();
thread2.start();
}
}
在这里,thread1和thread2共享哪个对象。我认为你错误地做线程对象的同步,而不是同步对象,这两个线程都是共享线程,这是线程2的对象,反之亦然。请考虑你的方法<代码> PASSON< <代码>。但是您没有访问
thread2
的任何资源/属性/方法。那你为什么要同步呢?锁定是在共享对象而不是线程对象上完成的。如果您还提供了线程的创建代码,请查看java.util.concurrent中的一些类。它们比同步、等待和通知更容易考虑。