创建线程的两种方法
##方法一 继承Thread类,需要用上所有方法(LSP原则)<不好>
public class Thread implements Runnable{
//code
}
public class MyThread extends Thread{
public void run(){
//重写run方法
}
}
//client端
MyThread p = new MyThread();
p.start;
##方法二 实现接口Runnable,Runnable接口中只有一个run方法 <好>
public class MyRunnable implements Runnable{
public void run(){
//重写run方法
}
}
//client端
//写法一:
MyRunnable p = new MyRunnable();
Thread p1 = new Thread(p);
p1.start;
/写法二
new Thread(new Runable(){
public void run(){
//重写run
}
}).start();
【创建进程步骤】:
1.创建Runnable对象
2.创建Thread对象
3.调用Thread.start()
4.进程thread开始运行
5.执行run
6.thread进程结束
中断进程
##Thread.sleep(time)&Thread.interrupt()
1.Thread.sleep()
线程休眠,休眠的线程不会失去对现有锁的所有权。
2.Thread.interrupt()
线程中断,停止run()的执行,中断结果取决于程序,可以return可以执行别的语句。【注意】:正常运行期间,即使接受到中断状态也不会理会,只有几个特殊操作(sleep,join)才能响应中断
检测是否中断:t.isInterrupted();//不影响中断状态
t.interrupted();//判断是否中断并且清除中断状态
(一)
1.public void run(){
2. try{
3. //code //正常运行期间可以接收到中断信号但是不理会
4. Thread.sleep(500);//sleep期间检测到中断信号,执行异常
5. }catch(InterruptedException e){
6. //code
7. }
8. //code
9.}
//main
10.t.start();
11.t.interrupt();//试图中断进程
执行顺序:11-4-6-8
(二)
1.pubilc void run(){
2. try{
3. while(!Thread.interrupted()){//接收到中断信号
4. Thread.sleep(500); //在sleep期间检测到中断信号才会响应
5. }
6. }catch(InterruptedException e){
7. //code
8. }
9. //code
10.}
//main
11.t.start();
12.t.interrupt();
执行顺序:11-4-7-9
(三)
1.public void run(){
2. try{
3. if(Thread.interrupted()){
4. throw new InterruptedException();
5. }
6. }catch(InterruptedExcption e){
7. //code
8. }
9. //code
10.}
//main
11.t.start();
12.t.interrupt();
执行顺序:12-4.7-9
(四)
1.public void run(){
2. try{
3. domethod();
4. }catch(InterruptedException e){
5. //code
6. }
7.}
8.public void demethod() throw InterruptedException{
9. if(Thread.isInterrupted)){
10. Thread.sleep(200);
11. }
12. //code
13.}
//main
14.t.start();
15.t.interrupt();
执行顺序:15-3-10-5
(五)
1.public void run(){
2. if(Thread.interrupted()){
3. //code
4. }else{
5. //code
6. }
7.}
//main
8.t1.start();
9.t1.interrupt();
10.t2.start();
执行顺序:t1 9-3; t2 10-5
【注意】:线程执行是不按照顺序的,但可以通过thread.join()使得先执行完一个进程再执行下一个进程
t1.start();
t1.join();
t2.start();
t2.join();