JAVA学习笔记-----线程

来源:互联网 发布:历史虚无主义表现知乎 编辑:程序博客网 时间:2024/06/05 03:06

线程的状态

这里写图片描述

线程基本控制方法

这里写图片描述

  1. sleep方法
    可以调用Thread的静态方法:
    public static void sleep(long millis) throws InterruptedException
    使当前线程休眠(暂时停止执行millis毫秒)
    由于是静态方法,sleep可以直接由类名调用:
    Thread.sleep(...)
  2. stop方法
    尽量不适用stop方法,太粗暴。
    使用类中设置变量,通过控制变量的方法控制线程结束。
  3. interrupt方法
    更改线程的状态为中断,如果重复调用,第一种可能清除中断状态,第二种可能抛出异常。
  4. join方法
    合并某个线程。
    举例说明:
public class TestJoin {  public static void main(String[] args) {    MyThread2 t1 = new MyThread2("t1");// 线程名字    t1.start(); // 启动一个分支    try {      t1.join(); // t1线程与当前线程合并,并执行t1线程的内容,后执行当前线程    } 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);  }  @Override  public void run() {    for (int i = 1; i <= 10; i++) {      System.out.println("i am " + getName());      try {        sleep(1000);      } catch (Exception e) {        return;      }    }  }}

执行结果

i am t1i am t1i am t1i am t1i am t1i am t1i am t1i am t1i am t1i am t1i am main threadi am main threadi am main threadi am main threadi am main threadi am main threadi am main threadi am main threadi am main threadi am main thread

分析:
t1.start()开始子线程,t1.join(),合并到主线程,但是先执行t1线程的内容,执行完毕后,顺序执行主线程。

yield方法

让出CPU,给其他线程执行的机会。(相当于阻塞自己,重新调度,下一次谁运行未知)

线程的优先级别

  • 线程的缺省优先级是5。
    一些常量:
    Thread.MIN_PRIORITY=1
    Thread.MAX_PRIORITY=10
    Thread.NORM_PRIORITY=5
    使用下述方法获得或设置线程对象的优先级:
    int getPriorith();
    void setPriority(int newPriority)

线程同步

关键字synchronized,互斥锁。
synchronized(){}:执行该语句块时,该语句块锁定。
synchronized方法名:表示整个方法为同步方法。虽然对象加锁,但是可以访问对象的其他方法。

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 void add(String name) {    synchronized (this) { //执行该语句块时,锁定当前对象      num++;      try {        Thread.sleep(1);      } catch (InterruptedException e) {      }      System.out.println(name + ", 你是第" + num + "个使用timer的线程");    }  }}class Timer {  private static int num = 0;  //执行该方法时,锁定当前对象  public synchronized void add(String name) {    num++;    try {      Thread.sleep(1);    } catch (InterruptedException e) {    }    System.out.println(name + ", 你是第" + num + "个使用timer的线程");  }}

模拟死锁问题

public class TestDeadLock implements Runnable {  public int flag = 1;  static Object o1 = new Object(), o2 = new Object();  public void run() {    System.out.println("flag=" + flag);    if (flag == 1) {      synchronized (o1) {        try {          Thread.sleep(500);        } catch (Exception e) {          e.printStackTrace();        }        synchronized (o2) {          System.out.println("1");        }      }    }    if (flag == 0) {      {        synchronized (o2) {          try {            Thread.sleep(500);          } catch (          InterruptedException e) {            e.printStackTrace();          }          synchronized (o1) {            System.out.println("0");          }        }      }    }  }  public static void main(String[] args) {    TestDeadLock td1 = new TestDeadLock();    TestDeadLock td2 = new TestDeadLock();    td1.flag = 1;    td2.flag = 0;    Thread t1 = new Thread(td1);    Thread t2 = new Thread(td2);    t1.start();    t2.start();  }}

分析:
t1锁定o1,睡眠0.5秒(执行t2),需要o2;
t2锁定o2,睡眠0.5秒,需要o1;
造成死锁现象。

wait和sleep方法区别

  1. wait时别的线程可以访问锁定对象

    • 调用wait方法的时候必须锁定该对象
  2. sleep时别的线程也不可以访问锁定对象
原创粉丝点击