1.继承Thread类
/**
* 用Thread类编写线程程序J_ThreadPrinter.java,实现数字和字母的打印:
* 线程A循环打印数字0-9,每次打印之间休眠500毫秒;
* 线程B循环打印字母‘A’-‘Z’, 每次打印之间休眠500毫秒;
* 查看结果并理解线程调度原理。
*/
public class J_ThreadPrinter {
public static void main(String[] args){
Thread A = new PrintNumberA();
A.start();
Thread B = new PrintCharacterA();
B.start();
}
}
class PrintNumberA extends Thread {
@Override
public void run() {
for (int i = 0; i <= 9; i++) {
System.out.print(i + ",");
try {
Thread.currentThread().sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class PrintCharacterA extends Thread {
@Override
public void run() {
for (char i = 'A'; i <= 'Z'; i++) {
System.out.print(i + ",");
try {
Thread.currentThread().sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
2.实现Runnable接口
/**
* 使用Runnable接口编写线程程序J_RunnablePrinter.java,实现数字和字母的打印:
* 线程A循环打印数字0-9,每次打印之间休眠500毫秒;
* 线程B循环打印字母‘A’-‘Z’, 每次打印之间休眠500毫秒;
* 查看结果并理解线程调度原理。
* 启动线程和线程休眠方法上的异同。
*/
public class J_RunnablePrinter {
public static void main(String[] args) {
Thread A = new Thread(new PrintNumberB());
A.start();
Thread B = new Thread(new PrintCharacterB());
B.start();
}
}
class PrintNumberB implements Runnable {
@Override
public void run() {
for (int i = 0; i <= 9; i++) {
System.out.print(i + ",");
try {
Thread.currentThread().sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class PrintCharacterB implements Runnable {
@Override
public void run() {
for (char i = 'A'; i <= 'Z'; i++) {
System.out.print(i + ",");
try {
Thread.currentThread().sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}