使用Runnable接口创建并启动两个线程一个线程输出1-50的数字另一个线程输出A-Z的大写和小写字母。2、在程序的main方法中先输出mainbegins分别创建和启动这两个线程然后输出mainends观察结果。
代码如下:
public class ThreadDemo implements Runnable {
private int type; // 1表示输出数字,2表示输出字母
private static Object lock = new Object();
public ThreadDemo(int type) {
this.type = type;
}
@Override
public void run() {
synchronized (lock) {
if (type == 1) {
for (int i = 1; i <= 50; i++) {
System.out.print(i + " ");
}
} else {
for (char c = 'A'; c <= 'Z'; c++) {
System.out.print(c + " ");
}
System.out.println();
for (char c = 'a'; c <= 'z'; c++) {
System.out.print(c + " ");
}
}
System.out.println();
}
}
public static void main(String[] args) {
System.out.println("main begins,");
Thread t1 = new Thread(new ThreadDemo(1));
Thread t2 = new Thread(new ThreadDemo(2));
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("main ends.");
}
}
输出结果:
main begins,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
a b c d e f g h i j k l m n o p q r s t u v w x y z
main ends.
可以看到,先输出了"main begins,",然后依次输出了数字和字母,并换行。最后输出了"main ends."。两个线程的输出顺序不一定完全一致,但是数字和字母的输出是交替的
原文地址: https://www.cveoy.top/t/topic/faQN 著作权归作者所有。请勿转载和采集!