十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
Java线程通信在使用的时候需要我们不断学习,在学习的时候会有很多的问题存在。其实我们在源代码中就能发现其中的奥秘。因为ThreadNum和ThreadChar都有对Objecto的引用,所以你wait和notify的时候都应该同步,Java线程通信具体看如下:

- public class Test8 {
 - public static void main(String[] args){
 - Object o=new Object();
 - Thread n=new ThreadNum(o);
 - Thread c=new ThreadChar(o);
 - n.start();
 - c.start();
 - }
 - }
 - class ThreadNum extends Thread{
 - Object o;
 - public ThreadNum(Object o){
 - this.o=o;
 - }
 - public void run(){
 - for(int i=1;i<26;i++){
 - System.out.println(i);
 - System.out.println(++i);
 - try {
 - synchronized (this) {
 - this.wait();
 - }
 - } catch (InterruptedException e) {}
 - synchronized (this) {
 - this.notify();
 - }
 - }
 - }
 - }
 - class ThreadChar extends Thread{
 - Object o;
 - public ThreadChar(Object o){
 - this.o=o;
 - }
 - public void run(){
 - for(char a='A';a<='Z';a++){
 - System.out.println(a);
 - synchronized (this) {
 - this.notify();
 - }
 - try {
 - synchronized (this) {
 - this.wait();
 - }
 - } catch (InterruptedException e) {}
 - }
 - }
 - }
 
以上就是对Java线程通信的详细介绍。