创建两个线程,一个输出偶数,一个输出奇数(包括基础版与进阶版两个版本)。
方式一基础版:
/**
* 创建两个线程,一个输出偶数,一个输出奇数。
* @author jerry
* @create 2020-12-27-10:37 AM
*/
public class ThreadDemo {
public static void main(String[] args) {
MyThrea1 t1 = new MyThrea1();
MyThrea2 t2 = new MyThrea2();
t1.start();
t2.start();
}
}
class MyThrea1 extends Thread {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
if (i % 2 == 0) {
System.out.println(Thread.currentThread().getName()+"偶数" + i);
}
}
}
}
class MyThrea2 extends Thread {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
if (i % 2 != 0) {
System.out.println(Thread.currentThread().getName() + "奇数" + i);
}
}
}
}
方式一进阶版:
/**
* @author jerry
* @create 2020-12-27-10:53 AM
*/
public class ThreadDemo1 {
public static void main(String[] args) {
new Thread() {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
if (i % 2 == 0) {
System.out.println("偶数" + i);
}
}
}
}.start();
new Thread() {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
if (i % 2 != 0) {
System.out.println("奇数" + i);
}
}
}
}.start();
}
}