最近看到一個(gè)多線程面試題,有三個(gè)線程分別打印A、B、C,請(qǐng)用多線程編程實(shí)現(xiàn),在屏幕上循環(huán)打印10次ABCABC…
看到這個(gè)題目,首先想到的是解決方法是定義一個(gè)Integer類對(duì)象,初始化為0,由3個(gè)線程共享,如果Integer對(duì)象取余3之后等于0,則打印A,同時(shí)進(jìn)行加1操作;如果Integer對(duì)象取3之后等于1,則打印B,同時(shí)進(jìn)行加1操作;如果Integer對(duì)象取3之后等于1,則打印C,如果循環(huán)打印了10次的話,就退出線程。
/** * ThreeThread * 3個(gè)線程測(cè)試 */ public class ThreeThread { public static void main(String[] args) throws InterruptedException { Integer gData = 0; Thread thread1 = new MyTask(gData, 0, "A"); Thread thread2 = new MyTask(gData, 1, "B"); Thread thread3 = new MyTask(gData, 2, "C"); thread1.start(); thread2.start(); thread3.start(); thread1.join(); thread2.join(); thread3.join(); } } class MyTask extends Thread { private Integer gData; p