---
title: "java的基本语法(六)"
author: "cfeers"
date: "2010-09-11T16:47:24Z"
tags: []
categories: ["编程语言"]
slug: "java"
draft: false
lastmod: "2010-09-11T16:47:24Z"
id: 760959
url: "https://cfeers.iteye.com/blog/760959"
---

**线程的一些笔记，入门。![](/images/smiles/icon_smile.gif)**                

            【第九章  线程】  run一结束，线程就结束

【线程】：是一个程序里面不同的执行路径。  java.lang.Thread

可以通过创建Thread的实例来创建新的线程。  
每个线程都是通过某个特定Thread对象所对应的方法run()来完成其操作的，方法run()称为线程体  
通过调用Thread类的【start()方法来启动一个线程】。\[使用strat才启用线程，run是线程实现的一个方法]

-----------------实现Runnable接口,还可以继承其他类实现其他接口，方法优于第二种--------  
public class TestThread1{  
 public static void main(String\[] args){  
  Runner1 r = new Runner1();  
  Thread t = new Thread(r);  
  t.start();    
  for(int i=0; i&lt;100; i++){  
   System.out.println("Main Thread:------" + i);   
  }   
 }   
}  
class Runner1 implements Runnable{  
 public void run(){  
  for(int i=0; i&lt;100; i++){  
   System.out.println("Runner1:"+ i);   
  }   
 }   
}  
\-----------------------继承Thread实现线程,方法较狭窄,不推荐使用-----------------------  
public class TestThread2{  
 public static void main(String\[] args){  
  Runner1 r = new Runner1();  
   r.start();   
  for(int i=0; i&lt;100; i++){  
   System.out.println("Main Thread:------" + i);   
  }   
 }   
}  
class Runner1 extends Thread{  
 public void run(){  
  for(int i=0; i&lt;100; i++){  
   System.out.println("Runner1:"+ i);   
  }   
 }   
}  
\--------------------------------------------------------------------------------------  
【线程状态】

线程控制基本方法：  
\==========================================================  
【方法】                   【功能】  
\-------------------------------------------------------------  
isAlive()           判断线程是否还"活"着,即线程是否还未终止  
\-------------------------------------------------------------  
getPriority()       获得线程的优先级数值      
\-------------------------------------------------------------  
setPriority()       设置线程的优先级数值  
\-------------------------------------------------------------  
Thread.sleep()      将当前线程睡眠指定毫秒数  
\-------------------------------------------------------------  
join()              调用某线程的该方法，将当前线程与该线程"合并"  
                   即等待该线程结束，再恢复当前线程的运行。  
\-------------------------------------------------------------  
yield()            让出cpu,当前线程进入就需队列等待调度  
\-------------------------------------------------------------  
wait()             当前线程进入对象的wait pool  
\-------------------------------------------------------------  
notify()             唤醒对象的wait pool 中的一个   
notifuAll()          /所有等待线程。  
\-------------------------------------------------------------

【sleep方法】      =&gt;&gt;&gt;在哪个线程调用sleep方法,就让哪个线程睡眠  
     可以调用Thread 的静态方法:  
       public static void sleep(long millis) throws InterruptedException  
       使得当前线程休眠(暂时停止执行millis毫秒)  
     优于是静态方法,sleep 可以由类名直接调用:  
       Thread.sleep();  
\----------------------------------------------------------------------   
import java.util.\*;  
public class TestThread3{  
 public static void main(String\[] args){  
  MyThread thread = new MyThread();  
  Thread t = new Thread(thread);  
  t.start();  
   try{  
     t.sleep(10000);  
   }catch(InterruptedException e){}  
      t.interrupt();  
 }   
}  
/*  
class MyThread  extends Thread{  
 public void run(){  
   while(true){  
    System.out.println("==="+ new Date()+"===");   
    try{  
     sleep(1000);   
    }catch(InterruptedException e){  
     return;   
    }  
   }  
  }   
 }  
\*/   
class MyThread implements Runnable{  
 public void run(){  
   while(true){  
    System.out.println("==="+ new Date()+"===");       
    try{  
     Thread.sleep(1000);   
    }catch(InterruptedException e){  
     return;   
    }  
    }  
   }    
 } 

 ------------------------------------------------------------------------  
【join方法】  
     合并某个线程

public class TestJoin{  
  public static void main(String\[] args){  
    MyThread2 t1 = new MyThread2("abcde");  
    t1.start();  
    try{  
     t1.join();   
    }catch(InterruptedException e){}  
       
    for(int i=1;i&lt;=10; i++){  
     System.out.println("i am mian thread");    
    }  
  }  
}  
class MyThread2 extends Thread{  
  MyThread2(String s){  
      super(s);   
  }   
 public void run(){  
  for(int i=1;i&lt;=10; i++){  
    System.out.println("i am "+getName());  
    try{  
      sleep(1000);   
    }catch(InterruptedException e){  
     return ;   
    }  
  }   
 }  
}  
\----------------------------------------------------------------------

【yield方法】  
     让出CPU，给其他线程执行的机会

public class TestYield{  
  public static void main(String\[] args){  
     MyThread3 t1 = new MyThread3("AAA--1-----");  
     MyThread3 t2 = new MyThread3("CCC--2-----");  
     t1.start(); t2.start();  
  }   
}  
class MyThread3 extends Thread{  
 MyThread3(String s){  
  super(s);   
 }   
 public void run(){  
  for(int i=1; i&lt;=100; i++){  
   System.out.println(getName()+": "+i);  
   if(i%10==0){  
    yield();   
   }   
  }   
 }  
}  
\----------------------------------------------------------------------  
线程的优先级用数字表示，范围从1到10，一个线程的缺省优先级是5.

  Thread.MIN\_PRIORITY = 1  
  Thread.MAN\_PRIORITY = 10  
  Thread.NORM\_PRIORITY = 5

使用下述线方法获得或设置线程对象的优先级。

  int getPriority();  
  void setPriority(int newPriority);  
\----------------------------------------------------------------------  
public class TestPriority{  
 public static void main(String\[] args){  
   Thread t1 = new Thread(new T1());  
   Thread t2 = new Thread(new T2());  
    t1.setPriority(Thread.NORM\_PRIORITY + 3);  
    t1.start();t2.start();  
 }   
}  
class T1 implements Runnable{  
 public void run(){  
  for(int i=0;i&lt;1000; i++){  
   System.out.println("T1:" + i);    
  }   
 }   
}

class T2 implements Runnable{  
 public void run(){  
   for(int i=0; i&lt;1000; i++){  
    System.out.println("----------T2:" + i);   
   }  
  }   
}

=======================================================================================  
\[线程同步]  
在java 语言中，引入了对象互斥锁的概念，保证共享数据操作的完整性。每个对象都对应于一个可称为  
"互斥锁"的标记，这个标记保证在任一时刻，只能有一个线程访问该对象。

关键字synchronized 来与对象的互斥锁联系。当某个对象synchronized 修饰时，表明该对象在任一时刻只能由一个线程访问。

synchronized 的使用方法：

 synchronized(this){  
      num ++;  
      try{Thread.sleep(1);}  
      catch(InterruptedException e){}  
      System.out.println(name+", 你是第"+num+"个使用timer的线程");   
 }  
也可以放在方法声明中，表示整个方法为同步方法,例如：

public synchronized void add(String name){...}

synchronized 执行方法的过程中，当前的对象被锁定,  
里面的成员对象也锁定(num),一个线程执行过程中不会被另一个线程打断

public class TestSync implements Runnable{  
 Timer timer = new Timer();  
 public static void main(String\[] args){  
   TestSync test = new TestSync();  
   Thread t1 = new Thread(test);  
   Thread t2 = new Thread(test);  
   t1.setName("t1");  
   t2.setName("t2");  
   t1.start();t2.start();   
 }   
 public void run(){  
    timer.add(Thread.currentThread().getName());   
 }  
}  
class Timer{  
 private static int num = 0;  
 public synchronized void add(String name){  
    //synchronized(this){  
   num ++;  
  try{  
    Thread.sleep(1);   
  }catch(InterruptedException e){}  
    System.out.println(name+", 你是第"+num+"个使用timer的线程");   
   // }  
 }   
}