JAVA中,启动线程的两种方法

1、继承继承Thread类, 重写run方法,在main函数中,调用start方法。代码如下:

  1. //播放音乐线程类  
  2. class MusicThread extends Thread {  
  3.     public void run() {  
  4.         for (int i = 0; i < 50; i++) {  
  5.             System.out.println("播放音乐" + i);  
  6.         }  
  7.     }  
  8. }  
  9.   
  10. //主线程类  
  11. public class ThreadDemo3 {  
  12.     public static void main(String[] args) {  
  13.   
  14.         //启动播放音乐的线程  
  15.         MusicThread thread1 = new MusicThread();  
  16.         thread1.start();  
  17.   
  18.         //主线程  
  19.         for (int i = 0; i < 50; i++) {  
  20.             System.out.println("打游戏" + i);  
  21.         }  
  22.     }  
  23. }  


2、实现Runnable接口,重写run方法,在main函数中,调用start方法。代码如下:

  1. //1):定义一个类A实现于java.lang.Runnable接口,注意A类不是线程类.  
  2. class MusicImplements implements Runnable{  
  3.     //2):在A类中覆盖Runnable接口中的run方法.  
  4.     public void run() {  
  5.         //3):在run方法中编写需要执行的操作  
  6.         for(int i = 0; i < 50; i ++){  
  7.             System.out.println("播放音乐"+i);  
  8.         }  
  9.           
  10.     }  
  11. }  
  12.   
  13. public class ImplementsRunnableDemo {  
  14.     public static void main(String[] args) {  
  15.         for(int j = 0; j < 50; j ++){  
  16.             System.out.println("运行游戏"+j);  
  17.             if(j == 10){  
  18.                 //4):在main方法(线程)中,创建线程对象,并启动线程  
  19.                 MusicImplements mi = new MusicImplements();  
  20.                 Thread t = new Thread(mi);  
  21.                 t.start();  
  22.             }  
  23.         }  
  24.     }  
  25.   
  26. }  

猜你喜欢

转载自blog.csdn.net/g1607058603/article/details/80727949