我正在尝试使用两个不同的线程按顺序打印从1到10的数字,但是输出并不总是相同

时间:2018-08-09 07:43:27

标签: java multithreading

这是我的代码的样子,代码有什么问题? 我想以1,2,3,4,... 10打印数字,但输出为2,1,3,4,6 ...并且每次都会更改,或者是实现此目的的更好方法< / p>

class Th1 extends Thread{
    public void run (){
        try{
            for (int i=1; i<=10; i+=2){
            System.out.println ("VALUE OF ODD : "+i);
            Thread.sleep (1000);
            }
        }catch (InterruptedException ie){
            System.out.println (ie);
        }
    }
};
class Th2 implements Runnable{
    public void run (){
        try{
            for (int j=2; j<=10; j+=2){
                System.out.println ("VALUE OF EVEN : "+j);
                Thread.sleep (1000);
            }
        }catch (InterruptedException ie){
            System.out.println (ie);
        }
    }
};
class ThDemo6{
    public static void main (String [] args)    {
        Th1 t1=new Th1 ();// object of Thread class
        Th2 t2=new Th2 ();// object of Runnable class
        Thread t=new Thread (t2);// Runnable is converted into Thread object
        System.out.println ("BEFORE START T1 IS : "+t1.isAlive ());
        System.out.println ("BEFORE START T2 IS : "+t.isAlive ());
        t1.start ();
        t.start ();
        System.out.println ("AFTER START T1 IS : "+t1.isAlive ());
        System.out.println ("AFTER START T2 IS : "+t.isAlive ());
        try        {
            t1.join ();// to make thread to join together for getting performance
            t.join ();
        }        catch (InterruptedException ie)        {
            System.out.println (ie);
        }
        System.out.println ("AFTER JOINING T1 IS : "+t1.isAlive ());
        System.out.println ("AFTER JOINING T2 IS : "+t.isAlive ());
    }
}

2 个答案:

答案 0 :(得分:1)

您无法控制哪个线程首先由调度程序获取CPU时间,因此输出可能永远不会按照您期望的顺序进行。 看一下Java线程模型和CPU调度。

编辑
当然,您可以在variabels等上使用锁,但这会损害线程的实际概念,即并行任务。 也许您应该检查是否有两个并行任务。我认为从1到X的计数是一项任务。

答案 1 :(得分:0)

代码有什么问题,它需要产生顺序的结果,但是您使用线程来做到这一点。

相关问题