方法一:继承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();
}
}
转载请注明原文地址:https://tech.qufami.com/read-2725.html