2个线程分别打印100内的奇数和偶数(java)

tech2022-08-18  121

方法一:继承Thread类的方式

public class ThreadDemo { public static void main(String[] args) { MyThread1 myThread1 = new MyThread1(); MyThread2 myThread2 = new MyThread2(); myThread1.start(); myThread2.start(); } } class MyThread1 extends Thread{ @Override public void run() { for (int i = 0; i < 100; i++) { if(i % 2 == 0){ System.out.println(currentThread().getName()+":"+i); } } } } class MyThread2 extends Thread{ @Override public void run() { for (int i = 0; i < 100; i++) { if(i % 2 != 0){ System.out.println(currentThread().getName()+":"+i); } } } }

用匿名子类的方式简化

public class ThreadDemo { 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(currentThread().getName()+":"+i); } } } }.start(); new Thread(){ @Override public void run() { for (int i = 0; i < 100; i++) { if(i % 2 != 0){ System.out.println(currentThread().getName()+":"+i); } } } }.start(); } }
最新回复(0)