多线程Thread类与Runnable接口

线程:

进程、线程都是实现并发机制的有效手段。

线程是比进程更小的执行单位,是在进程基础上的进一步划分。

一个程序运行,可能多个线程同时运行。

Thread类

Thread类属于java.lang.Object。在文档中的定义:public class Thread extends Object implements Runnable

可以看出,Thread类也实现了Runnable接口,一个类要继承thread类必须重写run()方法。

  1. public class MyThread extends Thread{  
  2.     private String name;//再类中定义一个属性  
  3.     public MyThread(String name){  
  4.         this.name = name;  
  5.     }  
  6. //  一定要重写Thread类中的run()方法,此方法为线程的主体  
  7.     public void run(){  
  8.         for(int i=0; i<10; i++){  
  9.             System.out.println(name+"运行, i="+i);  
  10.         }  
  11.     }  
  12. }  
  1. public class ThreadDemo01 {  
  2.     public static void main(String[] args) {  
  3.         MyThread mt1 = new MyThread("线程A");  
  4.         MyThread mt2 = new MyThread("线程B");  
  5.         mt1.run();  
  6.         mt2.run();  
  7.     }  
  8. }  

Runnable接口

  1. public class MyThread2 implements Runnable{  
  2.     private String name;  
  3.     public MyThread2(String name){  
  4.         this.name = name;  
  5.     }  
  6. //  重写Runnable接口中的run()方法  
  7.     public void run(){  
  8.         for(int i=0; i<10; i++){  
  9.             System.out.println(name+"运行, i="+i);  
  10.         }  
  11.     }  
  12. }  
  1. public class ThreadDemo04 {  
  2.     public static void main(String[] args) {  
  3.         MyThread2 mt1 = new MyThread2("线程A");  
  4.         MyThread2 mt2 = new MyThread2("线程B");  
  5.         Thread t1 = new Thread(mt1);  
  6.         Thread t2 = new Thread(mt2);  
  7.         t1.start();  
  8.         t2.start();  
  9.     }  
  10. }  

猜你喜欢

转载自blog.csdn.net/qq_39134392/article/details/80327410