Java笔记15:多线程

Java实现多线程有两种方式:一是继承Thread类;二是实现Runable接口。

一、Thread实现

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. publicclass ThreadDemo2 {  
  2.   
  3.     publicstaticvoid main(String[] args) {  
  4.   
  5.         new TestThread2().start();  
  6.   
  7.         inti = 0;  
  8.   
  9.         while(i++ < 100) {  
  10.   
  11.             System.out.println("main thread is running");  
  12.   
  13.         }  
  14.   
  15.     }  
  16.   
  17. }  
  18.   
  19.    
  20.   
  21. class TestThread2 extends Thread {  
  22.   
  23.     publicvoid run() {  
  24.   
  25.         intj = 0;  
  26.   
  27.         while(j++ < 100) {  
  28.   
  29.             System.out.println(Thread.currentThread().getName() + " is running!");  
  30.   
  31.         }  
  32.   
  33.     }  
  34.   
  35. }  

运行结果:

 

二、Runnable实现

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. publicclass ThreadDemo3 {  
  2.   
  3.     publicstaticvoid main(String[] args) {  
  4.   
  5.         TestThread3 t3 = new TestThread3();  
  6.   
  7.         Thread t = new Thread(t3);  
  8.   
  9.         t.start();  
  10.   
  11.         inti = 0;  
  12.   
  13.         while(i++ < 100) {  
  14.   
  15.             System.out.println("main thread is running");  
  16.   
  17.         }          
  18.   
  19.     }  
  20.   
  21. }  
  22.   
  23.    
  24.   
  25. class TestThread3 implements Runnable {  
  26.   
  27.     publicvoid run() {  
  28.   
  29.         intj = 0;  
  30.   
  31.         while(j++ < 100) {  
  32.   
  33.             System.out.println(Thread.currentThread().getName() + " is running!");  
  34.   
  35.         }  
  36.   
  37.     }  
  38.   
  39. }  

运行结果:

 

原文地址:https://www.cnblogs.com/grimm/p/6732497.html