如何使Java中的线程同时运行

Neo*_*Neo 1 java multithreading concurrent-programming

我正在尝试这个代码,我对我得到的输出有点困惑/惊讶.我还是Java新手,但我知道线程通常应该同时运行.看来我的"printB"线程在开始执行之前等待"printA"线程.我已经多次运行该程序(希望得到两个线程结果的混合,即类似:a,a,b,a,b,a ......)但仍然得到相同的输出(即"A"在"B"之前先打印.为什么会发生这种情况?如何更改代码以开始正常运行?

任何意见/建议将不胜感激.谢谢.

另外,我正在使用extends Thread方法尝试相同的代码,但它不起作用.

class PrintChars implements Runnable{
    private char charToPrint;
    private int times;

    public PrintChars(char c, int t){
        charToPrint = c;
        times = t;        
    }


    public void run(){
        for (int i=0; i<times; i++)
        System.out.println(charToPrint);        
    }


    public static void main(String[] args){

        PrintChars charA = new PrintChars('a', 7);
        PrintChars charB = new PrintChars('b', 5);

        Thread printA = new Thread(charA);
        Thread printB = new Thread(charB);

        printA.start();
        printB.start();
    }
}
Run Code Online (Sandbox Code Playgroud)

扩展Thread方法如下:

class PrintChars extends Thread {

private Char charToPrint;
private int times;


public PrintChars(char c, int t){
    charToPrint = c;
    times = t;
}


public void run (){

    for(int i =0; i<times; i++)
            System.out.println(charToPrint);
    }

    PrintChars printA = new PrintChars('a', 7);
    PrintChars printB = new PrintChars('a', 5);

    printA.start();
    printB.start();
}  
Run Code Online (Sandbox Code Playgroud)

Jea*_*ier 6

在多线程中,通常你不能对输出做任何假设.

也许用于创建线程的时间非常长,因此前一个线程有时间完全完成,因为它的执行非常短.

尝试使用7000和5000而不是7和5.