当前位置: 代码迷 >> 综合 >> 线程继承Thread和implements Runnable 交替运行
  详细解决方案

线程继承Thread和implements Runnable 交替运行

热度:0   发布时间:2023-12-22 16:00:02.0
public class MyThread extends Thread {volatile boolean keepRunning = true;int count = 0;//成员变量public void run() {System.out.println(getName() + "是一个Thread线程:");System.out.println(getName() + "线程开始了");while (keepRunning) {System.out.println(getName() + "启动:" + (++count));if (count == 100) {keepRunning = false;}if (count % 10 == 0) {try {Thread.sleep(1000);//若果count%10==0让线程休眠1s} catch (InterruptedException e) {e.printStackTrace();}}}System.out.println(getName() + "线程结束了");}public static void main(String[] args) {//main启动后立即结束,其他线程再执行,是一个异步过程System.out.println(Thread.currentThread().getName() + "启动");Thread thread = new MyThread();//多态,父类指向子类thread.setName("thread");thread.start();Thread thread1=new Thread(new MyRunnable(),"runnable");thread1.start();System.out.println(Thread.currentThread().getName() + "结束");}
}
class MyRunnable implements Runnable{volatile boolean keepRuning=true;int count=0;@Overridepublic void run() {System.out.println(Thread.currentThread().getName()+"线程开始了");while (keepRuning) {System.out.println(Thread.currentThread().getName()+"运行了:"+(count++));if(count==100){keepRuning=false;}if(count%10==0){try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}}System.out.println(Thread.currentThread().getName()+"线程结束了");}
}
  相关解决方案