多线程
实现方法
-
继承Thread类,重写run方法
public class Thread01 { public static void main(String[] args) { Cat cat = new Cat(); cat.start(); //主线程并不会阻塞,不会阻塞在start方法 for (int i = 0; i < 10; i++) { System.out.println(Thread.currentThread().getName()); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } } } class Cat extends Thread{ int times = 0; @Override public void run() { while (true){ System.out.println("第"+(++times)+"次喵喵"); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } if (times==10){ break; } } } }
-
实现Runnable接口,重写run方法(避免单继承的限制)
-
当某类继承了某个父类,但又实现多线程,可以实现此接口
-
更加适合多个线程共享一个资源。
public class Tread02 { public static void main(String[] args) { Dog dog = new Dog(); //使用代理模式(静态代理模式),dog实现了Runnalbe接口 // 构造方法:thread(Runnale tager) Thread thread = new Thread(dog); thread.start(); } } class Dog implements Runnable{ int times = 0; @Override public void run() { while (true){ System.out.println("第"+(++times)+"次汪汪"); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } if (times==10){ break; } } } }
-
多线程机制
-
start方法会开启一个子线程,如果直接调用run方法,那它也只有一个主线程。并没有体现出多线程
-
实现步骤
public synchronized void start() { //里面有个本地方法 start0(); } private native void start0();//底层c/C++实现,jvm实现 //实际上是start0()调用Run,实现子线程 start0().run();
线程终止
-
完成任务后,线程退出
-
使用变量,终止线程
常用方法
-
interrupt() 中断线程,(将休眠的线程唤醒)
-
setName() 设置线程名称
-
getName() 返回该线程的名称
-
start() 是该线程执行
-
run 调用线程对象Run方法
-
setPriority() 更改线程的优先级
-
getPriority() 获取线程的优先级
-
sleep() 指定的毫秒内让当前正在执行的线程休眠
-
yield(): 线程的礼让,让出cpu,让其他线程执行,但礼让的事件不确定,所以也不一定礼让成功
-
join() 线程的插队,插队成功,则先执行完插入的线程的所有任务。
public class Method_ { public static void main(String[] args) throws InterruptedException { T t = new T(); t.start(); for (int i = 0; i < 20; i++) { System.out.println("hello"); Thread.sleep(1000); if (i == 5) { System.out.println("t插队"); t.join(); } } } } class T extends Thread { @Override public void run() { while (true) { for (int i = 0; i < 20; i++) { System.out.println("hi"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } break; } } }
互斥锁
-
对象互斥锁,保证数据操作的完整性
-
保证任意时刻,只能有一个线程访问该对象
-
synchronized修饰
-
局限性:执行效率低
-
同步方法(非静态)的锁可以是this(本身),也可以是其他对象(要求是同一个对象)
-
同步方法(静态)的锁为当前类本身,当前类.class
-
同步方法
-
同步代码块
释放锁
-
当前线程的同步方法,同步代码块执行结束
-
当前线程在同步代码块、同步方法中遇到break,return;
-
出现了未处理的Error或Exception,导致异常结束
-
执行了wait()方法,暂停线程,释放锁
不会释放锁
-
Thread.sleep(),yield()
-
线程执行代码块时,其他线程挂起该线程,该线程不会释放锁
-
suspend() 和resume()不在推荐使用