0%
前言
线程学习笔记
创建线程
继承Thread
- 定义Thread的子类
- 重写run()方法
- 在run()方法中的代码,是与其他代码并行执行的代码
- 线程启动后,自动执行run()方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| package io.github.feiju12138;
public class Test { public static void main(String[] args) { TestThread thread = new TestThread(); thread.start(); } public static class TestThread extends Thread { public void run() { ... } } }
|
实现Runnable
- 定义Runnable子类
- 实现run()方法
- 把Runnable对象放入Thread线程对象启动
- 线程启动后,执行Runnable对象的run()方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| package io.github.feiju12138;
public class Test { public static void main(String[] args) { TestRunnable runnable = new TestRunnable(); Thread thread = new Thread(runnable); thread.start(); } public static class TestRunnable implements Runnable { public void run() { ... } } }
|
线程的方法
获得线程对象
获得线程名
设置线程名
暂停线程
<sun>
:当前线程暂停指定的毫秒值
打断一个线程的暂停状态
- 被打断的线程出现InterruptedException异常
当前线程,等待被调用的线程结束
- 一个线程调用另一个线程,等待另一个线程执行结束,再继续执行
让步,当前线程放弃时间片,让出cpu资源
优先级
1 2
| getPriority() setPriority()
|
后台线程
多线程的数据访问冲突
- 多个线程,共享访问数据
- 一个线程访问到修改的一半的数据,成为脏数据
线程同步
- 同步:多个线程,步调一致地执行
- 让多个线程,争夺同一个对象的“同步锁”,谁抢到谁执行,抢不到要等待
- 同步锁
- 任何对象,都有唯一的同步锁
- 遇到同步关键字(
synchronized
),要先抢到锁才能执行,抢不到要等待
同步代码块
<obj>
:指定对象
1 2 3
| synchronized(<obj>) { ... }
|
在方法上加锁
1 2 3
| synchronized void func() { ... }
|
静态同步代码块
1 2 3
| static synchronized void func() { ... }
|
完成