线程使用
线程——程序内部不同的执行路径。
创建线程有两种方式:
A、继承java.lang.Thread类。
class ThreadTest extends Thread{ public void run() { System.out.println ("someting run here!"); } public void run(String s){ System.out.println ("string in run is " + s); } public static void main (String[] args) { ThreadTest tt = new ThreadTest(); tt.start(); tt.run("it won't auto run!"); } }B、实现java.lang.Runnable接口。
class ThreadTest implements Runnable { public void run() { System.out.println ("someting run here"); } public static void main (String[] args) { ThreadTest tt = new ThreadTest(); Thread t1 = new Thread(tt); Thread t2 = new Thread(tt); t1.start(); t2.start(); //new Thread(tt).start(); } }常用方法:
isAlive();判断是否是活动的,终止就是死了,没有就绪也是死的,其余都是活动的。
getPriority();获得线程的优先级数值
setPriority();设置线程的优先级数值
Thread.sleep();当前线程睡眠指定毫秒数
join();调用某线程的该方法,将当前线程于该线程“合并”,即等待该线程结束,再恢复当前线程的运行。
yield();让出CPU,当前线程进入就绪队列等待调度。
wait();当前线程,进入对象的wait pool
notify()/notifyAll();唤醒对象的wait pool 中的一个/所有等待的线程。
interrupt() 中断线程。
停止线程很好的办法是在run();外定义一个boolean类型,外面通过传值判断就行了!
public class TestInterrupt {public static void main(String[] args) {MyThread td=new MyThread();td.start();try {Thread.sleep(10000);td.flag=false;} catch (InterruptedException e) {}}}class MyThread extends Thread{public boolean flag=true;@Overridepublic void run() {super.run();while (flag) {System.out.println("----"+new Date());try {sleep(1000);} catch (InterruptedException e) {return;}}}}