或者使用多线程打印

时间:2013-11-05 15:31:22

标签: java multithreading nullpointerexception runtimeexception

我对程序运行的分析但不是那样发生的事情::

-I在main方法中创建了2个线程,即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

OUTPUT ::

1
1
2

有谁能告诉我这是什么问题?

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

2 个答案:

答案 0 :(得分:0)

Thread t;未初始化。

System.out.println(t.getName()+" has "+i); //您将在此处获得例外

答案 1 :(得分:0)

- 因为每个帖子都有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
相关问题