Search code examples
javamultithreadingprintingrunnablesimultaneous

Why Char won't print, and counter exceeded my loop;


I am trying to run this three simultaneous threads, but when I do system.print Char won't come out, and the counter "i" went over bound.

somehow, I add an string in front of Char, it print out correctly, anyone can explain to me why is this happening?

    public class Part2 {
    public static void main(String[] args) {            
        Runnable printA = new PrintChar('a');
        Runnable printB = new PrintChar('b');
        Runnable printC = new PrintChar('c');

        Thread t1 = new Thread(printA);
        Thread t2 = new Thread(printB);
        Thread t3 = new Thread(printC);

        t1.start();
        t2.start();
        t3.start();     
    }

    private static class PrintChar implements Runnable { 
        private char c;
        public PrintChar(char c) {
            this.c = c;
        }

        public void run() 
        { 
            for(int i = 1; i<=100; i++) {
                System.out.print(c + i + ", ");
            }
        } 
    } 
    }

/*this is the output of this code: 98, 100, 101, 102, 103, 104, 105, 99, 99, .... 198, */

/*if I add a String before Char like this This is the output I expected; */

        public void run() 
        { 
            for(int i = 1; i<=100; i++) {
                System.out.print("" + c + i + ", ");
            }
        } 

/* b1, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18,.... a1 ~ a100 b1 ~ b100 and c1 ~ c100 runs and finish simultaneously */


Solution

  • When you use the + operator on a char and an int, it performs arithmetic addition, not string concatenation. Putting "" + first means you're first doing "" + c, which is concatenation into a String, then adding that String to an int, which is another concatenation.