线程总结(一)

主要内容

  1. 线程概念
  2. 创建线程的两个方法
    1. 实现runnable()接口
    2. 重写Thread类中方法
    3. 两种方法的区别
  3. 创建线程与方法调用区别
  4. 停止线程的两个方法
    1. interrupt()强制打断
    2. 引入变量boolean flag 控制
  5. Thread类常用方法
    1. sleep()
    2. interrupt()
    3. join()
    4. yield()
    5. setPriority(int newPriority)

线程:是程序的不同执行路径

一般操作系统支持多线程,多进程。dos支持单进程。

一个cpu,实质上只能支持一个线程执行,只是cpu运行速度快,看起来像是多线程。如果是双cpu或双核,可以执行多进程。

java中的线程是由java.lang.Thread类实现的

/**
 * 
 *程序功能:创建线程方法一(常用方法)
 * @author Administrator
 */
public class Test {
    //
    public static void main(String[] args) {
        // TODO Auto-generated constructor stub
        Run r=new Run();
        //通过Thread的实例化创建新的线程
        Thread t=new Thread(r);
        //启动线程,自动执行重写的run()方法
        t.start();
        
        //虚拟机启动时会自动创建一个有主方法定义的线程主线程。
        //主线程调用的方法
        for(int i=0;i<100;i++){
            System.out.println("Main Thread"+i);
            
        }
        
    }

}

//通过实现Runnable接口来重写run()方法
class Run implements Runnable{

    //启动新创建的线程时调用的方法
    public void run() {
        // TODO Auto-generated method stub
        for(int i=0;i<100;i++){
            System.out.println("new Thread"+i);
            
        }
        
    }
    
}

/**
 * 
 *程序功能:调用方法
 * @author Administrator
 */
public class Test2 {

    public static void main(String[] args) {
        // TODO Auto-generated constructor stub
        Run r=new Run();
        //方法调用
        r.run();
        //Thread t=new Thread(r);
        //t.start();
        
        
        for(int i=0;i<100;i++){
            System.out.println("Main Thread"+i);
            
        }

    }

}


class Run implements Runnable{

    
    public void run() {
        // TODO Auto-generated method stub
        for(int i=0;i<100;i++){
            System.out.println("new Thread"+i);

        }

    }

}

创建线程与方法调用区别

创建线程前,执行main方法中的语句,创建线程后,main方法未执行的语句与

创建线程后自动调用的语句并行执行,直到两者都执行完毕

方法调用前,执行main方法中的语句,执行到方法调用时,先停止执行main方法,执行调用的方法,当调用的方法执行完后,再继续执行main方法中还未执行的语句

/**
 * 
 *程序功能:创建线程方法二
 * @author Administrator
 */


public class Test2{
    public static void main(String[] args){
        Run t=new Run();
        t.start();
        
        for(int i=0;i<10;i++){
            System.out.println("主线程"+i);
        }
        
    }
}



class Run extends  Thread{
    public void run(){
        for(int i=0;i<10;i++)
        System.out.println("新线程");
    }
}

一般用方法一创建线程。因为java中的类只能继承一个类,但是可以实现很多接口。如果创建的自定义线程类继承了Thread类,那么他在无法继承其他类,就无法实现更复杂的功能

Thread类常用方法:

public static void sleep(long mills)throws InterruptedException:

使当前进程休眠(暂时停止执行mills毫秒)

在哪个线程里调用sleep方法,哪个线程陷入睡眠状态

void stop():已过时,在需要杀死线程时使用

void interrupt():中断线程

import java.util.Date;
/**
 * 
 *程序功能:不太合理的停止新建线程方法
 * @author Administrator
 */

public class Test {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Thread t=new Thread(new Runner());
        t.start();
        try {
            //主线程睡眠10s
            t.sleep(10000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //强制打断线程运行,引发Runner类中异常
        t.interrupt();
    }

}

class Runner implements Runnable{

    @Override
    public void run() {
        // TODO Auto-generated method stub
        Thread t=new Thread();
        while(true){
            System.out.println("---"+new Date()+"---");
            try {
                //睡眠1s
                t.sleep(1000);
            } catch (InterruptedException e) {
                // 结束方法
                return;
            }
        }
        
    }
    
    
}
/**
 * 
 *程序功能:停止创建的线程
 * @author Administrator
 */


import java.util.*;
public class Test2 {
  public static void main(String[] args) {
    MyThread thread = new MyThread();
    thread.start();
    try {Thread.sleep(10000);}
    catch (InterruptedException e) {}
    thread.flag=false;
  }
}

class MyThread extends Thread {
    boolean flag = true;
  public void run(){
    while(flag){
      System.out.println("==="+new Date()+"===");
      try {
        sleep(1000);
      } catch (InterruptedException e) {
        return;
      }
    }
  }
}

import java.util.Date;

public class Test {
  public static void main(String[] args) {
      Runner r=new Runner();
      Thread t=new Thread(r);
      t.start();
      for(int i=0;i<10;i++){
          System.out.println("主线程"+i);
      }

      r.shutDown();
  }
}

class Runner implements Runnable{
    boolean flag=true;
    public void run(){
        int i=0;
        while(flag){
            System.out.println("新线程"+i++);
            
        }
    }
    public void shutDown(){
        flag=false;
    }
}

void join():合并某个线程,相当于方法调用

public class Test {
  public static void main(String[] args) {
    MyThread2 t1 = new MyThread2("abcde");
    t1.start();
    try {
        t1.join();
    } catch (InterruptedException e) {}
        
    for(int i=1;i<=10;i++){
      System.out.println("i am main thread");
    }
  }
}
class MyThread2 extends Thread {
  MyThread2(String s){
      super(s);
  }
  
  public void run(){
    for(int i =1;i<=10;i++){
      System.out.println("i am "+getName());
      try {
          sleep(1000);
      } catch (InterruptedException e) {
          return;
      }
    }
  }
}
public static void yield():让出CPU,给其他线程执行的机会,但只让一下 
public class TestYield {
  public static void main(String[] args) {
    MyThread3 t1 = new MyThread3("t1");
    MyThread3 t2 = new MyThread3("t2");
    t1.start(); t2.start();
  }
}
class MyThread3 extends Thread {
  MyThread3(String s){super(s);}
  public void run(){
    for(int i =1;i<=100;i++){
      System.out.println(getName()+": "+i);
      if(i%10==0){
        yield();
      }
    }
  }
}

线程优先级越高,得到的cpu执行时间片越多

线程优先级范围:1-10(默认为5)

public static final int MAX_PRIORITY:最高优先级。
public static final int NORM_PRIORITY:默认优先级
public static final int MIN_PRIORITY:最低优先级
public final int getPriority():返回线程的优先级
public final 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<1000; i++) {
            System.out.println("T1: " + i);
        }
    }
}

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

参考资料:尚学堂马士兵java视频

原文地址:https://www.cnblogs.com/shangshicc/p/3731006.html