进程和线程
对上图说明如下:
- 方法区和堆是在一个进程内的,即多个线程共享
- 虚拟机栈和程序计数器每个线程都有属于自己的一套
理解:进程相当于大家合租房子,线程相当于每个人,方法区和堆相当于公共厨房、客厅,大家可以共享这些区域,虚拟机栈和程序计数器相当于每个小卧室,只有线程自己才能访问。
为什么要用多线程
设想这样一种情况,将文件A从C盘移动到D盘,将文件B从E盘移动到F盘,现在有两种解决方案(单核CPU):
- 先移动A,完成后再移动B
- 同时移动A和B
那么,哪种方式更快呢?
是方案一,因为同时移动A和B需要CPU反复切换增加了时间。但这是不是说,单进程/线程就比多进程/线程好呢?
创建方式 1
// 1. create a subclass extends Thread
class MyThread extends Thread {
// 2. override run method
public void run() {
for (int i = 0; i < 100; i++) {
if (i % 2 == 0) {
System.out.println(i);
}
}
}
}
public class ThreadTest {
public static void main(String[] args) {
// 3. 创建子类对象
MyThread myThread = new MyThread();
// 4. 调用start方法
myThread.start();
System.out.println("hello");
for (int i = 0; i < 100; i++) {
if (i % 2 != 0) {
System.out.println(i + "***");
}
}
}
}
创建Thread匿名子类
我们可以用下面方法来创建和上述代码相同的功能。
new Thread() {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
if (i % 2 == 0) {
System.out.println(i + Thread.currentThread().getName());
}
}
}
}.start();
注意
- 不可以通过直接调用run方法来启动线程,那样还是主线程在干活。
- 已经start的线程不能再start,会报IllegalThreadStateException异常,只能新建一个线程来start。
- 使用Thread.currentThread().getName() 可以看见当前线程名。
常用方法
setName
setName以及通过构造器给线程命名:
class TestThread extends Thread {
public TestThread(String name) {
super(name);
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
if (i % 2 != 0) {
System.out.println(Thread.currentThread().getName() + ":" + i);
}
}
}
}
public class ThreadMethodTest {
public static void main(String[] args) {
TestThread t1 = new TestThread("No.1"); // 使用构造器命名
// t1.setName("Num 1"); 调用setName方法命名
t1.start();
}
}
yield
释放当前CPU执行权。
join
线程1调用了线程2的join方法,那么线程1就进入阻塞状态,等线程2执行结束之后线程1才能继续执行。
sleep
让当前线程睡眠,在睡眠时间内,当前线程是阻塞状态
isAlive
判断当前线程是否存活
线程的优先级
创建方式 2
先用一个例子引入:
public class SellTicket {
public static void main(String[] args) {
Sell s1 = new Sell("No.1");
Sell s2 = new Sell("No.2");
Sell s3 = new Sell("No.3");
s1.start();
s2.start();
s3.start();
}
}
class Sell extends Thread {
private static int ticket = 100;
public Sell(String name) {
super(name);
}
public void run() {
while (true) {
if (ticket > 0) {
System.out.println(getName() + ":票号-" + ticket);
ticket--;
}
else {
break;
}
}
}
}
说明:100张票,三个线程卖,如果给票数加static,那么会卖出300张票,加了static后,大体是正确的,但是:
我们会发现票号为100卖出了三张,这个问题先保留,后面再解决。
public class Method2 {
public static void main(String[] args) {
Method_2 method_2 = new Method_2();
Thread thread = new Thread(method_2);
thread.start();
}
}
class Method_2 implements Runnable {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
if (i % 2 == 0) {
System.out.println(Thread.currentThread().getName() + ":" + i + " " + Thread.currentThread().getPriority());
}
}
}
}
说明:
- 我们先实现了Runnable接口
- 再去实现run方法
- 创建实现类的对象(这里是Method_2)
- 把这个对象作为参数传到Thread的构造器中,得到Thread的对象
- 使用该对象调用start方法
疑问:
- 为什么Thread的对象thread调用start会执行接口中的run方法?
start方法有两个作用:- 开启线程
- 执行run方法
通过查看源码:
发现Thread中的run方法调用了target:
而这个target是个Runnable类型的接口,
我们又通过构造器将Runnable的实现类对象传了进来,构成多态,因此调用实现类中的run方法。
我们再来看一下买票的那个代码,现在可以通过这种方式解决了:
public class SellTicket2 {
public static void main(String[] args) {
Sell2 sell2 = new Sell2();
Thread thread = new Thread(sell2);
Thread thread1 = new Thread(sell2);
Thread thread2 = new Thread(sell2);
thread.start();
thread1.start();
thread2.start();
}
}
class Sell2 implements Runnable {
private int ticket = 100;
@Override
public void run() {
while (true) {
if (ticket > 0) {
System.out.println(Thread.currentThread().getName() + ":票号-" + ticket);
ticket--;
}
else {
break;
}
}
}
}
为什么这种情况不用给ticket加static呢?因为实现类的对象只有一个,三个Thread的对象参数都是sell2,共用一个引用,因此不用加static。
两种创建方式的比较
线程的生命周期
线程的安全问题
方式 1 同步代码块 (实现runnable接口)
前面卖票的代码提到过,会出现三张票都是100的情况,我们如果做以下改动:
public class SellTicket2 {
public static void main(String[] args) {
Sell2 sell2 = new Sell2();
Thread thread = new Thread(sell2);
Thread thread1 = new Thread(sell2);
Thread thread2 = new Thread(sell2);
thread.start();
thread1.start();
thread2.start();
}
}
class Sell2 implements Runnable {
private int ticket = 100;
@Override
public void run() {
while (true) {
if (ticket > 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ":票号-" + ticket);
ticket--;
}
else {
break;
}
}
}
}
在if里加了个sleep,运行结果如下:
竟然出现了票号为-1的情况,原因如下:
- 当剩余票数为1张时,假设线程1执行到了if语句,满足大于0的条件,但这时它不会继续执行而是会阻塞100ms,因此票数不会-1,在这个期间线程2也执行到了if语句同样会阻塞,线程3同理。等阻塞结束时三个线程会将票数都-1,因此会出现负数。
关于重票和错票的问题可以看:https://www.bilibili.com/video/BV1Kb411W75N?p=432
方式 1 同步代码块 (继承Thread类)
回到这种方式的代码:
public class SellTicket {
public static void main(String[] args) {
Sell s1 = new Sell("No.1");
Sell s2 = new Sell("No.2");
Sell s3 = new Sell("No.3");
s1.start();
s2.start();
s3.start();
}
}
class Sell extends Thread {
private static int ticket = 100;
// static Object obj = new Object();
public Sell(String name) {
super(name);
}
public void run() {
while (true) {
// synchronized (obj) {
if (ticket > 0) {
System.out.println(getName() + ":票号-" + ticket);
ticket--;
} else {
break;
}
// }
}
}
}
之前说过,会有重复票的问题,我们想使用synchronized来解决,于是将if和else用synchronized包裹住并传入一个对象:
Object obj = new Object();
synchronized (obj) {
if (ticket > 0) {
System.out.println(getName() + ":票号-" + ticket);
ticket--;
} else {
break;
}
}
但结果还是有重复票的情况,原因是使用继承的方式,在本例中new了3个Sell对象,每个对象都有一个obj对象(互不相同),因此要把这个obj对象弄成静态的:
- static Object obj = new Object();
synchronized能否使用this?
- 对于继承Thread的方式,要慎用this,因为每个this都是new出来的对象,互不相同,起不到同一把锁的作用。后面会学到反射,类也是一个对象,因此可以把类传进来,先挖坑。
- 对于实现runnable接口的方式,可以使用this(但也要视具体情况定),因为调用run的就是接口实现类的对象,前面源码提到了。
- 可以看视频了解:https://www.bilibili.com/video/BV1Kb411W75N?p=434
方式2 同步方法 (实现runnable接口)
我们可以把需要同步的代码封装到函数中,如上例我们可以做如下处理:
public class SellTicket2 {
public static void main(String[] args) {
Sell2 sell2 = new Sell2();
Thread thread = new Thread(sell2);
Thread thread1 = new Thread(sell2);
Thread thread2 = new Thread(sell2);
thread.start();
thread1.start();
thread2.start();
}
}
class Sell2 implements Runnable {
private int ticket = 100;
Object obj = new Object();
@Override
public void run() {
while (true) {
method();
}
}
public synchronized void method() {
if (ticket > 0) {
System.out.println(Thread.currentThread().getName() + ":票号-" + ticket);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
ticket--;
}
}
}
只需要在函数名处加一个synchronized就可以了,不需要在设置锁,因为这种情况下默认的锁是this,而这三个对象共用this。
方式2 同步方法 (继承Thread)
public class SellTicket {
public static void main(String[] args) {
Sell s1 = new Sell("No.1");
Sell s2 = new Sell("No.2");
Sell s3 = new Sell("No.3");
s1.start();
s2.start();
s3.start();
}
}
class Sell extends Thread {
private static int ticket = 100;
public Sell(String name) {
super(name);
}
public void run() {
while (true) {
method();
}
}
public synchronized void method() { // 错误的方式
// public static synchronized void method() { 正确的方式
if (ticket > 0) {
System.out.println(Thread.currentThread().getName() + ":票号-" + ticket);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
ticket--;
}
}
}
这里method方法中默认的锁还是this,这就有问题了,因为三个对象三个this,就是三把锁。
解决方案是将这个方法弄成静态的,这样三个对象就是在同一个位置进行操作了,但synchronized要有锁,对于实现接口的方式来说,默认的是this,对于现在这种方式,锁默认是当前类本身(静态同步方法锁是类本身)。
同步的优劣
- 好处:解决了线程的安全问题
- 缺点:在操作同步代码时,只能有一个线程参与,相当于是单线程
线程安全的单例模式
单例模式的懒汉式会有线程安全的问题,先来回顾一下懒汉式的代码:
public class SingleModeSafe {
}
class SingleMode {
private SingleMode() {
}
private static SingleMode s = null;
public static SingleMode getInstance() {
if (s == null) {
s = new SingleMode();
}
return s;
}
}
为什么会有线程安全的问题?当有多个线程各自调用getInstance,当某线程执行到if语句时(假设首次调用,那么s==null),但这时此线程可能阻塞,其他的线程也会执行到if语句,所以s是共享数据,会被多次赋值。
用线程同步解决这个问题:
方法1
class SingleMode {
private SingleMode() {
}
private static SingleMode s = null;
public static SingleMode getInstance() {
synchronized (SingleMode.class) {
if (s == null) {
s = new SingleMode();
}
return s;
}
}
}
但这种方式效率太低,因为每个进程都要进去判断一下s是否为空,如果s被创建之后其他的线程不再判断s是否为空效率就高了:
public static SingleMode getInstance() {
if (s == null) {
synchronized (SingleMode.class) {
if (s == null) {
s = new SingleMode();
}
}
}
return s;
}
这样一旦s创建之后,其他的线程再来就不会执行if里面的了。
死锁问题
https://www.bilibili.com/video/BV1Kb411W75N?p=438
Lock方式解决线程安全问题
import java.util.concurrent.locks.ReentrantLock;
public class LockTest {
public static void main(String[] args) {
Window window = new Window();
Thread t1 = new Thread(window);
Thread t2 = new Thread(window);
Thread t3 = new Thread(window);
t1.start();
t2.start();
t3.start();
}
}
class Window implements Runnable {
private int tickets = 100;
private ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
while (true) {
try {
lock.lock();
if (tickets > 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ":票号-" + tickets);
tickets--;
} else {
break;
}
}finally{
lock.unlock();
}
}
}
}
synchronized和lock对比
一道练习题
public class DepositTest {
public static void main(String[] args) {
Account account = new Account(0);
Customer c1 = new Customer(account);
Customer c2 = new Customer(account);
c1.start();
c2.start();
}
}
class Customer extends Thread{
private Account acco;
public Customer(Account acco) {
this.acco = acco;
}
@Override
public void run() {
for (int i = 0; i < 3; i++) {
acco.deposit(1000);
}
}
}
class Account {
private int remain;
public Account(int num) {
remain = num;
}
public void deposit(int money) {
if (money > 0) {
remain += money;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + "余额为: " + remain);
}
}
上述代码结果如下:
因为在 remain += money;之后sleep了,在这个睡眠期间两个线程都执行了加钱操作而没有马上输出,因此线程0输出结果是在线程1加钱之后,所以看到的结果是2000,解决方案是给deposit方法加上static。
注意,这个例子中是继承了Thread,但synchronized方法里使用this就可以了,因为调用deposit的对象是两个线程共用的。
线程的通信
现在想线程1和线程2交替打印1-100:
public class ThreadCommunication {
public static void main(String[] args) {
Show show = new Show();
Thread t1 = new Thread(show);
Thread t2 = new Thread(show);
t1.setName("NO.1");
t2.setName("NO.2");
t1.start();
t2.start();
}
}
class Show implements Runnable {
private int num = 1;
@Override
public void run() {
while (true) {
synchronized (this) {
notify();
if (num <= 100) {
System.out.println(Thread.currentThread().getName() + ": " + num);
num += 1;
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
else {
break;
}
}
}
}
}
注意:
sleep和wait的异同
不同点第三条:sleep()不会释放同步监视器,wait()会释放。
JDK 5.0新增创建线程的方式
新增方式1 实现Callable接口
FutureTask实现了RunnableFuture,而后者继承Runnable接口,因此FutureTask它的对象可以作为参数传到Thread的构造器中。
现在的目的是获取FutureTask的对象,而FutureTask构造器之一是:
也就是说需要一个Callable的对象传入,而Callable是一个接口,那么用一个类实现此接口并将该类对象传入FutureTask构造器即可得到FutureTask的对象。
有了FutureTask的对象就可以得到Thread的对象了,进而可以调用start()
步骤:
比较实现Callable和Runnable
再对整个过程做一个梳理:
- new Thread(futureTask).start();通过这句代码来执行目标程序
- 我们知道Thread中是有start方法的,且Thread的构造器接收的参数是Runnable类型。而这个FutureTask前面说过,它实现了RunnableFuture接口,而后者继承了Runnable, Future,也就是说FutureTask的对象可以作为参数传到Thread的构造器里面
- Thread中的start方法调用了start0方法,后者又调用了target的run方法(这个target就是FutureTask的对象,futureTask),而这个run方法已经被FutureTask重写过了,在run方法中,又由callable调用了call方法(callable是FutureTask构造器的参数,为Callable类型),因此如果一个类实现了Callable的call方法,那么最终调用的就是此call方法
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
public class CallableTest {
public static void main(String[] args) {
NumberThread numberThread = new NumberThread();
FutureTask futureTask = new FutureTask(numberThread);
new Thread(futureTask).start();
}
}
class NumberThread implements Callable {
@Override
public Object call() throws Exception {
int sum = 0;
for (int i = 0; i <= 100; i++) {
if (i % 2 == 0) {
System.out.println(i);
sum += i;
}
}
return sum;
}
}
新增方式2 使用线程池
https://www.bilibili.com/video/BV1Kb411W75N?p=446