实现多线程

  1. 继承Thread方法,重写run方法
  2. 实习Runnable接口,实现run方法

继承Thread和实现Runnable的区别:

  1. 实现Runnable可以实现代码共享,即同一个代码段可以被多个Thread来启动
  2. 继承Thread要想实现代码共享,必须在synchronized代码块应用class literal(类名称字面常量),即synchronized(Xxx.class),而synchronized(this)不好使

synchronized用法

  1. 可以在方法前边加上synchronized修饰符
  2. 在方法插入synchronized块,
  • synchronized(this)

此种方法只能是同一个对象锁,若是new出来的两个对象不会有任何锁限定

  • synchronized(Xxx.class)

此种方法对同一个文件生成的所有对象都会生成锁

继承Thread类如下: 

 

 
  
  1. package thread; 
  2. /** 
  3.  * @author zcb zhengchangbai@163.com 
  4.  * @date 2011-11-28 上午12:23:49 
  5.  */ 
  6. public class ExtendsThread extends Thread{ 
  7.     private static int ticket = 10
  8.     public ExtendsThread(){ 
  9.         super(); 
  10.     } 
  11.     public ExtendsThread(String name){ 
  12.         super(name); 
  13.     } 
  14.     @Override 
  15.     public void run() { 
  16.         for (int i = 0; i < 10; i++) { 
  17.              
  18.             //下面是class,所有该class的对象都互斥,而this只对 对象互斥 
  19.             synchronized (ExtendsThread.class) {   
  20.                  
  21.                 ticket--; 
  22.                 System.out.println(Thread.currentThread().getName()+":"+ticket); 
  23.             } 
  24.              
  25.             try { 
  26.                 Thread.sleep(10); 
  27.             } catch (InterruptedException e) { 
  28.                 e.printStackTrace(); 
  29.             } 
  30.         } 
  31.          
  32.     } 
  33.     
  34.     public static void main(String[] args) { 
  35.         Thread thread = new ExtendsThread("Thread-A"); 
  36.         Thread thread2 = new ExtendsThread("Thread-B"); 
  37.          
  38.         thread.start(); 
  39.         thread2.start(); 
  40.     } 

实现Runnable接口:

 

 
  
  1. package thread; 
  2. /** 
  3.  * @author zcb zhengchangbai@163.com 
  4.  * @date 2011-11-28 上午12:24:56 
  5.  */ 
  6. public class ImplementRunnable implements Runnable { 
  7.     private static int tickets = 10
  8.     @Override 
  9.     public void run() { 
  10.         for (int i = 0; i < 10; i++) { 
  11.              
  12.             synchronized (this) {  
  13.                 tickets--; 
  14.                 System.out.println(Thread.currentThread().getName()+":"+tickets); 
  15.             } 
  16.             try { 
  17.                 Thread.sleep(10); 
  18.             } catch (InterruptedException e) { 
  19.                 e.printStackTrace(); 
  20.             } 
  21.         } 
  22.     } 
  23.      
  24.     public static void main(String[] args) { 
  25.         Runnable r = new ImplementRunnable(); 
  26.          
  27.         Thread thread = new Thread(r,"Thread-A"); 
  28.         Thread thread2 = new Thread(r,"Thread-B"); 
  29.          
  30.         thread.start(); 
  31.         thread2.start(); 
  32.     } 
  33.