Java新建线程的两种方式

时间:2021-12-04 01:35:48

  Java新建线程有两种方式,一种是通过继承Thread类,一种是实现Runnable接口,下面是新建线程的两种方式。

  我们假设有个竞赛,有一个选手A做俯卧撑,一个选手B做仰卧起坐。分别为两个线程:

playerA.java

public class playerA extends Thread {

    @Override
public void run() {
System.out.println("选手A出场了!");
boolean flag=true;
int count=0;
while (flag) {
System.out.println(getName()+"做了"+(++count)+"个俯卧撑");
if (count==100) {
flag=false;
}
if(count%10==0) {
try {
sleep(2000);//线程休息了2秒
System.out.println(getName()+"的2秒休息完了");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
System.out.println(getName()+"做完了"+count+"个俯卧撑"); } }

playerB.java

public class playerB implements Runnable {

    @Override
public void run() {
System.out.println("选手B出场了!");
boolean flag=true;
int count=0;
while (flag) {
System.out.println(Thread.currentThread().getName()+"做了"+(++count)+"个仰卧起坐");
if (count==100) {
flag=false;
}
if(count%10==0) {
try {
Thread.sleep(2000);//线程休息了2秒
System.out.println(Thread.currentThread().getName()+"的2秒休息完了");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
System.out.println(Thread.currentThread().getName()+"做完了"+count+"个仰卧起坐"); } }

competitionDrive.java

public class competitionDrive {

    public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("比赛开始了"); //两种创建线程方式
Thread A=new playerA();
A.setName("选手A");
A.start(); Thread B=new Thread(new playerB(),"选手B");
B.start(); } }