Threads communication can use share resource,eg.(var,file)
or function.eg. The thread1 will notify thread2 print a string "Hello thread2 "class Thread1 extends Thread
{ thread2 = new Thread2();
public Thread1()
{ start();
}
public void run()
{ while(true)
{
try{sleep(2000);}
catch(InerruptException e){}
thread1.sayHello("Hello thread2 !");
}
}
class Thread2 extends Thread
{ private s;
public void sayHello(String s)
{ this.s = s;
}
public void run()
{ while(true){
try{sleep(2000);}
catch(InerruptException e){}
if(s != null)
System.out.println(s);
s = null;
}
}
} public static main(String[] arg)
{ thread2.start();
new Thread1();
}}该给分了!
or function.eg. The thread1 will notify thread2 print a string "Hello thread2 "class Thread1 extends Thread
{ thread2 = new Thread2();
public Thread1()
{ start();
}
public void run()
{ while(true)
{
try{sleep(2000);}
catch(InerruptException e){}
thread1.sayHello("Hello thread2 !");
}
}
class Thread2 extends Thread
{ private s;
public void sayHello(String s)
{ this.s = s;
}
public void run()
{ while(true){
try{sleep(2000);}
catch(InerruptException e){}
if(s != null)
System.out.println(s);
s = null;
}
}
} public static main(String[] arg)
{ thread2.start();
new Thread1();
}}该给分了!
or function.eg. The thread1 will notify thread2 print a string "Hello thread2 "class Thread1 extends Thread
{ thread2 = new Thread2();
public Thread1()
{ start();
}
public void run()
{ while(true)
{
try{sleep(2000);}
catch(InerruptException e){}
thread1.sayHello("Hello thread2 !");
}
}
class Thread2 extends Thread
{ private String s;
public void sayHello(String s)
{ this.s = s;
}
public void run()
{ while(true){
try{sleep(2000);}
catch(InerruptException e){}
if(s != null)
System.out.println(s);
s = null;
}
}
} public static main(String[] arg)
{ thread2.start();
new Thread1();
}}
for example, two threads running on different hosts have no chance to access the same object, but only know the existence of each other, and communication has to be published before anything can be transmitted and shared.