第一种写法
public class ABCD {
public static void main(String[] args) throws InterruptedException {
boolean f = true;
int shuru = 0;
while(f){
Scanner scanner = new Scanner(System.in);
System.out.println("请输入正整数");
String s = scanner.nextLine();
System.out.println("您输入 = "+s);
try{
shuru =Integer.parseInt(s);
if(shuru >0){
f = false;
}else{
System.out.println("请输入正整数!");
}
}catch(Exception e){
}
}
for(int i = 1; i<=shuru ; i++){
AtomicInteger flag = new AtomicInteger(0);
Runnable A = new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
System.out.print("A");
flag.addAndGet(1);
}
};
Runnable B = new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
System.out.print("B");
flag.addAndGet(1);
}
};
Runnable C = new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
System.out.print("C");
flag.addAndGet(1);
}
};
Runnable D = new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
System.out.print("D");
flag.addAndGet(1);
}
};
Thread a = new Thread(A);
Thread b = new Thread(B);
Thread c = new Thread(C);
Thread d = new Thread(D);
a.start();
a.join();
b.start();
b.join();
c.start();
c.join();
d.start();
d.join();
}
}
}
第二种写法
public class ABCD2 {
public static void main(String[] args) {
ExecutorService executorService = Executors.newSingleThreadExecutor();
for(int i =0 ;i <10; i++){
MyThread A = new MyThread("A");
executorService.submit(A);
MyThread B = new MyThread("B");
executorService.submit(B);
MyThread C = new MyThread("C");
executorService.submit(C);
MyThread D = new MyThread("D");
executorService.submit(D);
}
}
}
class MyThread implements Runnable{
public MyThread(String name){
this.name = name;
}
private String name;
@Override
public void run() {
// TODO Auto-generated method stub
System.out.print(name);
}
}
第三种写法
List<MyThread> list = new ArrayList<MyThread>();
for(int i =0 ;i <10; i++){
MyThread A = new MyThread("A");
list.add(A);
MyThread B = new MyThread("B");
list.add(B);
MyThread C = new MyThread("C");
list.add(C);
MyThread D = new MyThread("D");
list.add(D);
}
for (MyThread myThread : list) {
Thread t = new Thread(myThread);
t.start();
try {
t.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}