有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用多线程交替打印

我对程序运行的分析,但并非如此:

-我在main方法中创建了两个线程,即Child1和Child2

-然后启动两个线程

-Child1作为一个单独的线程进入run()方法,并进入synchronized块,打印1并由于调用了wait方法而休眠

-Child2作为一个单独的线程进入run()方法,并进入synchronized块,打印1并通知Child1唤醒

-此过程持续5分钟

package multi_threading;

public class inter_thread implements Runnable {
    static inter_thread obj;
    boolean val=false;
    Thread t;

    public inter_thread(){}
    public inter_thread(String msg){
        t=new Thread(obj,msg);
        t.start();
    }
    public static void main(String args[]){
        obj=new inter_thread();
        inter_thread obj1=new inter_thread("Child1"); 
        inter_thread obj2=new inter_thread("Child2");
        try{
            obj1.t.join();
            obj2.t.join();
        }catch(InterruptedException e){
            System.out.println("Interrupted");
        }
    }

    public void run(){
        int i;
        synchronized(obj){
        for(i=1;i<=5;i++){
            System.out.println(i);
            val=!val;
            while(val)
                try{
                    wait();
                }catch(InterruptedException e){
                    System.out.println("Interrupted");
            }
            notify();
        }
     }
    }

}

我想使用多线程显示如下输出:

1
1
2
2
3
3
4
4
5
5

输出::

1
1
2

谁能告诉我有什么问题吗

EDIT2::我已经编辑了前面的代码


共 (2) 个答案

  1. # 1 楼答案

    -因为每个线程都有一个obj副本,所以我刚刚得到

    1
    1
    2
    

    作为输出

    我修改了程序,使线程Child1和Child2共享对象

    package multi_threading;
    
     public class inter_thread {
        Thread t;
        public inter_thread(test_value obj,String msg){
            t=new Thread(obj,msg);
            t.start();
        }
    
    }
    
     class test_value implements Runnable{
         boolean val=false;
        public static void main(String args[]){
            test_value obj=new test_value();
            inter_thread obj1=new inter_thread(obj,"Child1"); 
            inter_thread obj2=new inter_thread(obj,"Child2");
            try{
                obj1.t.join();
                obj2.t.join();
            }catch(InterruptedException e){
                System.out.println("Interrupted");
            }
        }
        public void run(){
            int i;
            synchronized(obj){
            for(i=1;i<=5;i++){
                System.out.println(i);
                obj.val=!obj.val;
                while(obj.val)
                    try{
                        wait();
                    }catch(InterruptedException e){
                        System.out.println("Interrupted");
                    }
                   notify();
               }
           }
        }
     }
    

    -我收到一个编译错误,表示无法解析obj

    -如何在线程之间共享obj以及如何生成如下输出:

    1
    1
    2
    2
    3
    3
    4
    4
    5
    5
    
  2. # 2 楼答案

    Thread t;未初始化

    System.out.println(t.getName()+" has "+i);//您将在此处遇到异常