目录
背景
优点
1.程序
2.进程
3.线程
4.程序与进程对比
5.线程的分类
1.继承于Thread类
1.1Thread类中的常用方法:
1.2线程的优先级
1.3同步代码块解决线程安全问题
1.4同步方法解决线程安全问题
2.实现Runnable接口
2.1同步代码块解决线程安全问题
2.2同步方法解决线程安全问题
3.解决线程安全问题的方式三:Lock锁 --- JDK5.0新增
4.比较创建线程方法:继承Thread方式和实现Runnable接口方式
5.实现Callable接口(JDK5.0新增)
6.使用线程池(JDK5.0新增)
6.1线程池相关API
三、线程的生命周期
四、线程的死锁问题
五、线程的通信
最后
背景
以单核CPU为例,只使用单个线程先后完成多个任务(调用多个方法),肯定比用多个线程来完成用的时间更短,为何仍需多线程呢?
优点
1.提高应用程序的响应。对图形化界面更有意义,可增强用户体验。
2.提高计算机系统CPU的利用率
3.改善程序结构。将既长又复杂的进程分为多个线程,独立运行,利于理解和修改
以单核CPU为例,只使用单个线程先后完成多个任务(调用多个方法),肯定比用多个线程来完成用的时间更短,为何仍需多线程呢?
1.提高应用程序的响应。对图形化界面更有意义,可增强用户体验。
2.提高计算机系统CPU的利用率
3.改善程序结构。将既长又复杂的进程分为多个线程,独立运行,利于理解和修改
一、基本概念
1.程序
程序(program)是为完成特定任务、用某种语言编写的一组指令的集合。即指一段静态的代码,静态对象。
2.进程
进程(process)是程序的一次执行过程,或是正在运行的一个程序。是一个动态的过程:有它自身的产生、存在和消亡的过程。——生命周期
如:运行中的QQ,运行中的MP3播放器
3.线程
线程(thread),进程可进一步细化为线程,是一个程序内部的一条执行路径。若一个进程同一时间并行执行多个线程,就是支持多线程的
线程作为调度和执行的单位,每个线程拥有独立的运行栈和程序计数器(pc),线程切换的开销小
一个进程中的多个线程共享相同的内存单元/内存地址空间→它们从同一堆中分配对象,可以访问相同的变量和对象。这就使得线程间通信更简便、高效。但多个线程操作共享的系统资源可能就会带来安全的隐患。
4.程序与进程对比
程序是静态的,进程是动态的
》进程作为资源分配的单位,系统在运行时会为每个进程分配不同的内存区域
5.线程的分类
二、多线程的创建和使用
1.继承于Thread类
步骤:
1.创建一个继承于Thread类的子类,
2.重写Thread类的run()-->将此线程执行的操作声明在run()中
3.创建Thread类的子类的对象。
4.通过此对象调用start()
//1.创建一个继承于Thread类的子类
class MyThread extends Thread{
//重写Thread类的run()
@Override
public void run() {
for(int i = 1;i < 100;i++){
if(i % 2 == 0){
System.out.println(i);
}
}
}
}
public class ThreadTest {
public static void main(String[] args) {
//3.创建Thread类的子对象
MyThread t1 = new MyThread();
//4.通过此对象调用start():①启动当前线程 ②调用当前线程的run()
t1.start();
//如下操作仍在main线程中执行的
for(int i = 1;i < 100;i++){
if(i % 2 == 0){
System.out.println(i + "***main()***");
}
}
}
}
1.1Thread类中的常用方法:
1. start():启动当前线程:调用当前线程的run()
2. run():通常需要重写Thread类中的此方法,将创建的线程要执行的操作声明在此方法中
3. currentThread ():静态方法,返回执行当前代码的线程
4.qetName();获取当前线程的名字
5.setName():设置当前线程的名字;
6. yield():释放当前cpu的执行权
7、join():在线程a中调用线程b的ioin(),此时线程a就进入阻塞状态,直到线程b完全执行完以后,线程a方向结束阻塞状态。8. stop():己过时。当执行此方法时,强制结束当前线程。
9. sleep(long millitime):让当前线程“缝隙”指定的millitime蓬勃。在指定的millitime蓬秒时间内,当前,线程是阻塞状态。
10.isAlive():判断当前线程是否存活
11.wait():让当前进程进入阻塞状态
12.notify():唤醒某一原本处于阻塞状态的进程
13.notifyAll():唤醒所有原本处于阻塞状态的进程
14.suspend():已过时,将线程挂起
15.resume():已过时,将挂起线程复活继续执行
1.2线程的优先级
1.
MAXPRIORITY :1θ
MINPRIORITY :1
NORMPRIORITY :5-->默认优先级
2.如何获取和设置当前线程的优先级:
getPriority ():获取线程的优先级
setPriority (int p):设置线程的优先级
注意:优先级高的线程比优先级低的线程具有比较高的概率会被优先执行,但不是百分之一百优先被执行
1.3同步代码块解决线程安全问题
class Windows extends Thread{
private static int ticket = 100;
private static Object obj = new Object();
@Override
public void run() {
while(true){
//正确的
// synchronized (obj) {
synchronized (Windows.class){ //Class clazz = Windows.class
//错误的,因为此时this表示的是t1,t2,t3三个对象
// synchronized (this) {
if (ticket > 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(getName() + ":卖票,票号为: " + ticket);
ticket--;
} else {
break;
}
}
}
}
}
public class WindowsTest2 {
public static void main(String[] args) {
Windows t1 = new Windows();
Windows t2 = new Windows();
Windows t3 = new Windows();
t1.setName("窗口1");
t2.setName("窗口2");
t3.setName("窗口3");
t1.start();
t2.start();
t3.start();
}
}
1.4同步方法解决线程安全问题
class Windows4 extends Thread {
private static int ticket = 100;
@Override
public void run() {
while (true) {
show();
}
}
private static synchronized void show(){//同步监视器:Window4.class
//private synchronized void show(){ //同步监视器:t1,t2,t3。此种解决方式是错误的
if (ticket > 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ":卖票,票号为:" + ticket);
ticket--;
}
}
}
public class WindowsTest4 {
public static void main(String[] args) {
Windows4 t1 = new Windows4();
Windows4 t2 = new Windows4();
Windows4 t3 = new Windows4();
t1.setName("窗口1");
t2.setName("窗口2");
t3.setName("窗口3");
t1.start();
t2.start();
t3.start();
}
}
2.实现Runnable接口
1.创建一个实现了Runnable接口的类?
2、实现类去实现Runnable中的抽象方法:run()
3.创建实现类的对象
4.将此对象作为参数传递到Thread类的构造器中,创建Thread类的对象。
5.通过Thread类的对象调用start()
//1.创建一个实现了Runnable接口得类
class MThread implements Runnable{
//2.实现类去实现Runnable中的抽象方法:run()
@Override
public void run() {
for(int i = 0;i < 100;i++){
if(i % 2 == 0){
System.out.println(Thread.currentThread().getName() + ":" + i);
}
}
}
}
public class ThreadTest1 {
public static void main(String[] args) {
//3.创建实现类的对象
MThread m1 = new MThread();
//4.将此对象作为参数传递到Thread类的构造器中,创建Thread类的对象
Thread t1 = new Thread(m1);
//5.通过Thread类的对象调用start():①启动线程 ②调用当前线程的run() --> 调用了Runnable类型的target的run()
t1.start();
//再启动一个线程,遍历100以内的偶数
Thread t2 = new Thread(m1);
t2.setName("线程2");
t2.start();
}
}
2.1同步代码块解决线程安全问题
class Dog{
}
class Windows1 implements Runnable{
private int ticket = 100;
// Object obj = new Object();
// Dog dog = new Dog();
@Override
public void run() {
while(true){
synchronized (this) {//此时的this:唯一的windows1的对象 //方式二:synchronized (dog) {
if (ticket > 0) {
try{
Thread.sleep(100);
}catch (InterruptedException e){
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ":卖票,票号为: " + ticket);
ticket--;
} else {
break;
}
}
}
}
}
public class WindowsTest1 {
public static void main(String[] args) {
Windows1 w = new Windows1();
Thread t1 = new Thread(w);
Thread t2 = new Thread(w);
Thread t3 = new Thread(w);
t1.setName("窗口1");
t2.setName("窗口2");
t3.setName("窗口3");
t1.start();
t2.start();
t3.start();
}
}
2.2同步方法解决线程安全问题
class Windows3 implements Runnable {
private int ticket = 100;
@Override
public void run() {
while (true) {
show();
}
}
public synchronized void show() { //同步监视器:this
// synchronized (this){
if (ticket > 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ":卖票,票号为: " + ticket);
ticket--;
}
// }
}
}
public class WindowsTest3 {
public static void main(String[] args) {
Windows3 w3 = new Windows3();
Thread t1 = new Thread(w3);
Thread t2 = new Thread(w3);
Thread t3 = new Thread(w3);
t1.setName("窗口1");
t2.setName("窗口2");
t3.setName("窗口3");
t1.start();
t2.start();
t3.start();
}
}
3.解决线程安全问题的方式三:Lock锁 --- JDK5.0新增
1.面试题:synchronized 与 Lock的异同?
相同:二者都可以解决线程安全问题
不同:synchronized机制在执行完相应的同步代码以后,自动的释放同步监视器
Lock需要手动的启动同步( Lock() ),同时结束同步也需要手动的实现( unLock() )
注意:在使用lock方法前要进行声明定义,如下所示
private ReentrantLock lock = new ReentrantLock();
//关锁
lock.lock();
...
//开锁
lock.unlock();
步骤:
1.创建一个继承于Thread类的子类,
2.重写Thread类的run()-->将此线程执行的操作声明在run()中
3.创建Thread类的子类的对象。
4.通过此对象调用start()
1. start():启动当前线程:调用当前线程的run()
2. run():通常需要重写Thread类中的此方法,将创建的线程要执行的操作声明在此方法中
3. currentThread ():静态方法,返回执行当前代码的线程
4.qetName();获取当前线程的名字
5.setName():设置当前线程的名字;
6. yield():释放当前cpu的执行权
7、join():在线程a中调用线程b的ioin(),此时线程a就进入阻塞状态,直到线程b完全执行完以后,线程a方向结束阻塞状态。8. stop():己过时。当执行此方法时,强制结束当前线程。
9. sleep(long millitime):让当前线程“缝隙”指定的millitime蓬勃。在指定的millitime蓬秒时间内,当前,线程是阻塞状态。
10.isAlive():判断当前线程是否存活11.wait():让当前进程进入阻塞状态
12.notify():唤醒某一原本处于阻塞状态的进程
13.notifyAll():唤醒所有原本处于阻塞状态的进程
14.suspend():已过时,将线程挂起
15.resume():已过时,将挂起线程复活继续执行
1.2线程的优先级
1.
MAXPRIORITY :1θ
MINPRIORITY :1
NORMPRIORITY :5-->默认优先级
2.如何获取和设置当前线程的优先级:
getPriority ():获取线程的优先级
setPriority (int p):设置线程的优先级
注意:优先级高的线程比优先级低的线程具有比较高的概率会被优先执行,但不是百分之一百优先被执行
1.3同步代码块解决线程安全问题
class Windows extends Thread{
private static int ticket = 100;
private static Object obj = new Object();
@Override
public void run() {
while(true){
//正确的
// synchronized (obj) {
synchronized (Windows.class){ //Class clazz = Windows.class
//错误的,因为此时this表示的是t1,t2,t3三个对象
// synchronized (this) {
if (ticket > 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(getName() + ":卖票,票号为: " + ticket);
ticket--;
} else {
break;
}
}
}
}
}
public class WindowsTest2 {
public static void main(String[] args) {
Windows t1 = new Windows();
Windows t2 = new Windows();
Windows t3 = new Windows();
t1.setName("窗口1");
t2.setName("窗口2");
t3.setName("窗口3");
t1.start();
t2.start();
t3.start();
}
}
1.4同步方法解决线程安全问题
class Windows4 extends Thread {
private static int ticket = 100;
@Override
public void run() {
while (true) {
show();
}
}
private static synchronized void show(){//同步监视器:Window4.class
//private synchronized void show(){ //同步监视器:t1,t2,t3。此种解决方式是错误的
if (ticket > 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ":卖票,票号为:" + ticket);
ticket--;
}
}
}
public class WindowsTest4 {
public static void main(String[] args) {
Windows4 t1 = new Windows4();
Windows4 t2 = new Windows4();
Windows4 t3 = new Windows4();
t1.setName("窗口1");
t2.setName("窗口2");
t3.setName("窗口3");
t1.start();
t2.start();
t3.start();
}
}
2.实现Runnable接口
1.创建一个实现了Runnable接口的类?
2、实现类去实现Runnable中的抽象方法:run()
3.创建实现类的对象
4.将此对象作为参数传递到Thread类的构造器中,创建Thread类的对象。
5.通过Thread类的对象调用start()
//1.创建一个实现了Runnable接口得类
class MThread implements Runnable{
//2.实现类去实现Runnable中的抽象方法:run()
@Override
public void run() {
for(int i = 0;i < 100;i++){
if(i % 2 == 0){
System.out.println(Thread.currentThread().getName() + ":" + i);
}
}
}
}
public class ThreadTest1 {
public static void main(String[] args) {
//3.创建实现类的对象
MThread m1 = new MThread();
//4.将此对象作为参数传递到Thread类的构造器中,创建Thread类的对象
Thread t1 = new Thread(m1);
//5.通过Thread类的对象调用start():①启动线程 ②调用当前线程的run() --> 调用了Runnable类型的target的run()
t1.start();
//再启动一个线程,遍历100以内的偶数
Thread t2 = new Thread(m1);
t2.setName("线程2");
t2.start();
}
}
2.1同步代码块解决线程安全问题
class Dog{
}
class Windows1 implements Runnable{
private int ticket = 100;
// Object obj = new Object();
// Dog dog = new Dog();
@Override
public void run() {
while(true){
synchronized (this) {//此时的this:唯一的windows1的对象 //方式二:synchronized (dog) {
if (ticket > 0) {
try{
Thread.sleep(100);
}catch (InterruptedException e){
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ":卖票,票号为: " + ticket);
ticket--;
} else {
break;
}
}
}
}
}
public class WindowsTest1 {
public static void main(String[] args) {
Windows1 w = new Windows1();
Thread t1 = new Thread(w);
Thread t2 = new Thread(w);
Thread t3 = new Thread(w);
t1.setName("窗口1");
t2.setName("窗口2");
t3.setName("窗口3");
t1.start();
t2.start();
t3.start();
}
}
2.2同步方法解决线程安全问题
class Windows3 implements Runnable {
private int ticket = 100;
@Override
public void run() {
while (true) {
show();
}
}
public synchronized void show() { //同步监视器:this
// synchronized (this){
if (ticket > 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ":卖票,票号为: " + ticket);
ticket--;
}
// }
}
}
public class WindowsTest3 {
public static void main(String[] args) {
Windows3 w3 = new Windows3();
Thread t1 = new Thread(w3);
Thread t2 = new Thread(w3);
Thread t3 = new Thread(w3);
t1.setName("窗口1");
t2.setName("窗口2");
t3.setName("窗口3");
t1.start();
t2.start();
t3.start();
}
}
3.解决线程安全问题的方式三:Lock锁 --- JDK5.0新增
1.面试题:synchronized 与 Lock的异同?
相同:二者都可以解决线程安全问题
不同:synchronized机制在执行完相应的同步代码以后,自动的释放同步监视器
Lock需要手动的启动同步( Lock() ),同时结束同步也需要手动的实现( unLock() )
注意:在使用lock方法前要进行声明定义,如下所示
private ReentrantLock lock = new ReentrantLock();
//关锁
lock.lock();
...
//开锁
lock.unlock();
1.
MAXPRIORITY :1θ
MINPRIORITY :1
NORMPRIORITY :5-->默认优先级
2.如何获取和设置当前线程的优先级:
getPriority ():获取线程的优先级
setPriority (int p):设置线程的优先级
注意:优先级高的线程比优先级低的线程具有比较高的概率会被优先执行,但不是百分之一百优先被执行
class Windows extends Thread{
private static int ticket = 100;
private static Object obj = new Object();
@Override
public void run() {
while(true){
//正确的
// synchronized (obj) {
synchronized (Windows.class){ //Class clazz = Windows.class
//错误的,因为此时this表示的是t1,t2,t3三个对象
// synchronized (this) {
if (ticket > 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(getName() + ":卖票,票号为: " + ticket);
ticket--;
} else {
break;
}
}
}
}
}
public class WindowsTest2 {
public static void main(String[] args) {
Windows t1 = new Windows();
Windows t2 = new Windows();
Windows t3 = new Windows();
t1.setName("窗口1");
t2.setName("窗口2");
t3.setName("窗口3");
t1.start();
t2.start();
t3.start();
}
}
1.4同步方法解决线程安全问题
class Windows4 extends Thread {
private static int ticket = 100;
@Override
public void run() {
while (true) {
show();
}
}
private static synchronized void show(){//同步监视器:Window4.class
//private synchronized void show(){ //同步监视器:t1,t2,t3。此种解决方式是错误的
if (ticket > 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ":卖票,票号为:" + ticket);
ticket--;
}
}
}
public class WindowsTest4 {
public static void main(String[] args) {
Windows4 t1 = new Windows4();
Windows4 t2 = new Windows4();
Windows4 t3 = new Windows4();
t1.setName("窗口1");
t2.setName("窗口2");
t3.setName("窗口3");
t1.start();
t2.start();
t3.start();
}
}
2.实现Runnable接口
1.创建一个实现了Runnable接口的类?
2、实现类去实现Runnable中的抽象方法:run()
3.创建实现类的对象
4.将此对象作为参数传递到Thread类的构造器中,创建Thread类的对象。
5.通过Thread类的对象调用start()
//1.创建一个实现了Runnable接口得类
class MThread implements Runnable{
//2.实现类去实现Runnable中的抽象方法:run()
@Override
public void run() {
for(int i = 0;i < 100;i++){
if(i % 2 == 0){
System.out.println(Thread.currentThread().getName() + ":" + i);
}
}
}
}
public class ThreadTest1 {
public static void main(String[] args) {
//3.创建实现类的对象
MThread m1 = new MThread();
//4.将此对象作为参数传递到Thread类的构造器中,创建Thread类的对象
Thread t1 = new Thread(m1);
//5.通过Thread类的对象调用start():①启动线程 ②调用当前线程的run() --> 调用了Runnable类型的target的run()
t1.start();
//再启动一个线程,遍历100以内的偶数
Thread t2 = new Thread(m1);
t2.setName("线程2");
t2.start();
}
}
2.1同步代码块解决线程安全问题
class Dog{
}
class Windows1 implements Runnable{
private int ticket = 100;
// Object obj = new Object();
// Dog dog = new Dog();
@Override
public void run() {
while(true){
synchronized (this) {//此时的this:唯一的windows1的对象 //方式二:synchronized (dog) {
if (ticket > 0) {
try{
Thread.sleep(100);
}catch (InterruptedException e){
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ":卖票,票号为: " + ticket);
ticket--;
} else {
break;
}
}
}
}
}
public class WindowsTest1 {
public static void main(String[] args) {
Windows1 w = new Windows1();
Thread t1 = new Thread(w);
Thread t2 = new Thread(w);
Thread t3 = new Thread(w);
t1.setName("窗口1");
t2.setName("窗口2");
t3.setName("窗口3");
t1.start();
t2.start();
t3.start();
}
}
2.2同步方法解决线程安全问题
class Windows3 implements Runnable {
private int ticket = 100;
@Override
public void run() {
while (true) {
show();
}
}
public synchronized void show() { //同步监视器:this
// synchronized (this){
if (ticket > 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ":卖票,票号为: " + ticket);
ticket--;
}
// }
}
}
public class WindowsTest3 {
public static void main(String[] args) {
Windows3 w3 = new Windows3();
Thread t1 = new Thread(w3);
Thread t2 = new Thread(w3);
Thread t3 = new Thread(w3);
t1.setName("窗口1");
t2.setName("窗口2");
t3.setName("窗口3");
t1.start();
t2.start();
t3.start();
}
}
3.解决线程安全问题的方式三:Lock锁 --- JDK5.0新增
1.面试题:synchronized 与 Lock的异同?
相同:二者都可以解决线程安全问题
不同:synchronized机制在执行完相应的同步代码以后,自动的释放同步监视器
Lock需要手动的启动同步( Lock() ),同时结束同步也需要手动的实现( unLock() )
注意:在使用lock方法前要进行声明定义,如下所示
private ReentrantLock lock = new ReentrantLock();
//关锁
lock.lock();
...
//开锁
lock.unlock();
1.创建一个实现了Runnable接口的类?
2、实现类去实现Runnable中的抽象方法:run()
3.创建实现类的对象4.将此对象作为参数传递到Thread类的构造器中,创建Thread类的对象。
5.通过Thread类的对象调用start()
//1.创建一个实现了Runnable接口得类
class MThread implements Runnable{
//2.实现类去实现Runnable中的抽象方法:run()
@Override
public void run() {
for(int i = 0;i < 100;i++){
if(i % 2 == 0){
System.out.println(Thread.currentThread().getName() + ":" + i);
}
}
}
}
public class ThreadTest1 {
public static void main(String[] args) {
//3.创建实现类的对象
MThread m1 = new MThread();
//4.将此对象作为参数传递到Thread类的构造器中,创建Thread类的对象
Thread t1 = new Thread(m1);
//5.通过Thread类的对象调用start():①启动线程 ②调用当前线程的run() --> 调用了Runnable类型的target的run()
t1.start();
//再启动一个线程,遍历100以内的偶数
Thread t2 = new Thread(m1);
t2.setName("线程2");
t2.start();
}
}
2.1同步代码块解决线程安全问题
class Dog{
}
class Windows1 implements Runnable{
private int ticket = 100;
// Object obj = new Object();
// Dog dog = new Dog();
@Override
public void run() {
while(true){
synchronized (this) {//此时的this:唯一的windows1的对象 //方式二:synchronized (dog) {
if (ticket > 0) {
try{
Thread.sleep(100);
}catch (InterruptedException e){
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ":卖票,票号为: " + ticket);
ticket--;
} else {
break;
}
}
}
}
}
public class WindowsTest1 {
public static void main(String[] args) {
Windows1 w = new Windows1();
Thread t1 = new Thread(w);
Thread t2 = new Thread(w);
Thread t3 = new Thread(w);
t1.setName("窗口1");
t2.setName("窗口2");
t3.setName("窗口3");
t1.start();
t2.start();
t3.start();
}
}
2.2同步方法解决线程安全问题
class Windows3 implements Runnable {
private int ticket = 100;
@Override
public void run() {
while (true) {
show();
}
}
public synchronized void show() { //同步监视器:this
// synchronized (this){
if (ticket > 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ":卖票,票号为: " + ticket);
ticket--;
}
// }
}
}
public class WindowsTest3 {
public static void main(String[] args) {
Windows3 w3 = new Windows3();
Thread t1 = new Thread(w3);
Thread t2 = new Thread(w3);
Thread t3 = new Thread(w3);
t1.setName("窗口1");
t2.setName("窗口2");
t3.setName("窗口3");
t1.start();
t2.start();
t3.start();
}
}
3.解决线程安全问题的方式三:Lock锁 --- JDK5.0新增
1.面试题:synchronized 与 Lock的异同?
相同:二者都可以解决线程安全问题
不同:synchronized机制在执行完相应的同步代码以后,自动的释放同步监视器
Lock需要手动的启动同步( Lock() ),同时结束同步也需要手动的实现( unLock() )
注意:在使用lock方法前要进行声明定义,如下所示
private ReentrantLock lock = new ReentrantLock();
//关锁
lock.lock();
...
//开锁
lock.unlock();
class Windows3 implements Runnable {
private int ticket = 100;
@Override
public void run() {
while (true) {
show();
}
}
public synchronized void show() { //同步监视器:this
// synchronized (this){
if (ticket > 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ":卖票,票号为: " + ticket);
ticket--;
}
// }
}
}
public class WindowsTest3 {
public static void main(String[] args) {
Windows3 w3 = new Windows3();
Thread t1 = new Thread(w3);
Thread t2 = new Thread(w3);
Thread t3 = new Thread(w3);
t1.setName("窗口1");
t2.setName("窗口2");
t3.setName("窗口3");
t1.start();
t2.start();
t3.start();
}
}
3.解决线程安全问题的方式三:Lock锁 --- JDK5.0新增
1.面试题:synchronized 与 Lock的异同?
相同:二者都可以解决线程安全问题
不同:synchronized机制在执行完相应的同步代码以后,自动的释放同步监视器
Lock需要手动的启动同步( Lock() ),同时结束同步也需要手动的实现( unLock() )
注意:在使用lock方法前要进行声明定义,如下所示
private ReentrantLock lock = new ReentrantLock();
//关锁
lock.lock();
...
//开锁
lock.unlock();
1.面试题:synchronized 与 Lock的异同?
相同:二者都可以解决线程安全问题
不同:synchronized机制在执行完相应的同步代码以后,自动的释放同步监视器
Lock需要手动的启动同步( Lock() ),同时结束同步也需要手动的实现( unLock() )
注意:在使用lock方法前要进行声明定义,如下所示
private ReentrantLock lock = new ReentrantLock(); //关锁 lock.lock(); ... //开锁 lock.unlock();
4.比较创建线程方法:继承Thread方式和实现Runnable接口方式
开发中:优先选择:实现Runnable接口的方式:
原因:
1.实现的方式没有类的单继承性的局限性:
2.实现的方式更适合来处理多个线程有共享数据的情况。
联系:public class Thread implements Runnable
相同点:两种方式都需要重写run(),将线程要执行的逻辑声明在run()中。
5.实现Callable接口(JDK5.0新增)
与使用Runnable相比,Callable功能更强大些
相比run()方法,可以有返回值
方法可以抛出异常
支持泛型的返回值
需要借助 FutureTask 类,比如获取返回结果
论如何理解实现Callable接口的方式创建多线程比实现Runnable接口创建多线程方式强大?
1. call()可以有返回值的。
2. call()可以抛出异常,被外面的操作捕获,获取异常的信息
3. Callable是支持泛型的
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
//1.创建一个实现Callable的实现类
class NumThread implements Callable{
//2.实现call方法,将此线程需要执行的操作声明在call()中
@Override
public Object call() throws Exception {
int sum = 0;
for(int i = 1;i <= 100;i++){
if(i % 2 == 0){
System.out.println(i);
sum += i;
}
}
return sum;
}
}
public class ThreadNew {
public static void main(String[] args) {
//3.创建Callable接口实现类的对象
NumThread numThread = new NumThread();
//4.将此Callable接口实现类的对象作为传递到FutureTask构造器中,创建FutureTask的对象
FutureTask futureTask = new FutureTask(numThread);
//5.将FutureTask的对象作为参数传递到Thread类的构造器中,创建Thread对象,并调用start()
new Thread(futureTask).start();
try {
//6.获取Callable中call方法的返回值
//get()返回值即为FutureTask构造器参数Callable实现类重写的call()的返回值。
Object sum = futureTask.get();
System.out.println("总和为:" + sum);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
开发中:优先选择:实现Runnable接口的方式:
原因:
1.实现的方式没有类的单继承性的局限性:
2.实现的方式更适合来处理多个线程有共享数据的情况。
联系:public class Thread implements Runnable
相同点:两种方式都需要重写run(),将线程要执行的逻辑声明在run()中。
与使用Runnable相比,Callable功能更强大些
相比run()方法,可以有返回值
方法可以抛出异常
支持泛型的返回值
需要借助 FutureTask 类,比如获取返回结果论如何理解实现Callable接口的方式创建多线程比实现Runnable接口创建多线程方式强大?
1. call()可以有返回值的。
2. call()可以抛出异常,被外面的操作捕获,获取异常的信息
3. Callable是支持泛型的
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
//1.创建一个实现Callable的实现类
class NumThread implements Callable{
//2.实现call方法,将此线程需要执行的操作声明在call()中
@Override
public Object call() throws Exception {
int sum = 0;
for(int i = 1;i <= 100;i++){
if(i % 2 == 0){
System.out.println(i);
sum += i;
}
}
return sum;
}
}
public class ThreadNew {
public static void main(String[] args) {
//3.创建Callable接口实现类的对象
NumThread numThread = new NumThread();
//4.将此Callable接口实现类的对象作为传递到FutureTask构造器中,创建FutureTask的对象
FutureTask futureTask = new FutureTask(numThread);
//5.将FutureTask的对象作为参数传递到Thread类的构造器中,创建Thread对象,并调用start()
new Thread(futureTask).start();
try {
//6.获取Callable中call方法的返回值
//get()返回值即为FutureTask构造器参数Callable实现类重写的call()的返回值。
Object sum = futureTask.get();
System.out.println("总和为:" + sum);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
6.使用线程池(JDK5.0新增)
好处:
1.提高响应速度(减少了创建新线程的时间)
2.降低资源消耗(重复利用线程池中线程,不需要每次都创建)
3.便于线程管理
corePoolSize :核心池的大小
maximumPoolSize :最大线程数
keepAliveTime :线程没有任务时最多保持多长时间后会终止
好处:
1.提高响应速度(减少了创建新线程的时间)
2.降低资源消耗(重复利用线程池中线程,不需要每次都创建)
3.便于线程管理
corePoolSize :核心池的大小
maximumPoolSize :最大线程数
keepAliveTime :线程没有任务时最多保持多长时间后会终止
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
class NumberThread implements Runnable{
@Override
public void run() {
for(int i = 0;i <= 100;i++){
if(i % 2 == 0){
System.out.println(Thread.currentThread().getName() + ":" + i);
}
}
}
}
class NumberThread1 implements Runnable{
@Override
public void run() {
for(int i = 0;i <= 100;i++){
if(i % 2 != 0){
System.out.println(Thread.currentThread().getName() + ":" + i);
}
}
}
}
public class ThreadPool {
public static void main(String[] args) {
//1. 提供指定线程数量的线程池
ExecutorService service = Executors.newFixedThreadPool(10);
ThreadPoolExecutor service1 = (ThreadPoolExecutor) service;
//设置线程池的属性
// System.out.println(service.getClass());
// service1.setCorePoolSize(15);
// service1.setKeepAliveTime();
//2.执行指定的线程的操作。需要提供实现Runnable接口或Callable接口实现类的对象
service.execute(new NumberThread()); //适合适用于Runable
service.execute(new NumberThread1()); //适合适用于Runable
// service.submit(Callable callable); //适合适用于Callable
//3.关闭连接池
service.shutdown();
}
}
6.1线程池相关API
1.JDK5.0起提供了线程池相关API: ExecutorService 和Executors
2.ExecutorService :真正的线程池接口。常见子类 ThreadPoolExecutor
》void execute(Runnable command):执行任务/命令,没有返回值,一般用来执行Runnable
》Futuresubmit(Callabletask):执行任务,有返回值,一般又来执行Callable
》void shutdown():关闭连接池
3.Executors:工具类、线程池的工厂类,用于创建并返回不同类型的线程池
》Executors. newCachedThreadPool ():创建一个可根据需要创建新线程的线程池
》Executors. newFixedThreadPool (n);创建一个可重用固定线程数的线程池
》Executors. newSingleThreadExecutor ():创建一个只有一个线程的线程池
》Executors. newScheduledThreadPool (n):创建一个线程池,它可安排在给定延迟后过行命令或者定期地执行。
三、线程的生命周期
1.JDK5.0起提供了线程池相关API: ExecutorService 和Executors
2.ExecutorService :真正的线程池接口。常见子类 ThreadPoolExecutor
》void execute(Runnable command):执行任务/命令,没有返回值,一般用来执行Runnable
》
》void shutdown():关闭连接池
3.Executors:工具类、线程池的工厂类,用于创建并返回不同类型的线程池
》Executors. newCachedThreadPool ():创建一个可根据需要创建新线程的线程池
》Executors. newFixedThreadPool (n);创建一个可重用固定线程数的线程池
》Executors. newSingleThreadExecutor ():创建一个只有一个线程的线程池
》Executors. newScheduledThreadPool (n):创建一个线程池,它可安排在给定延迟后过行命令或者定期地执行。
四、线程的死锁问题
1.死锁的理解:不同的线程分别占用对方需要的同步资源不放弃,都在等待对方放弃自己需要的同步资源,就形成了线程的死锁
2.说明:(1)出现死锁后,不会出现异常,不会出现提示,只是所有的线程都处于阻塞状态,无法继续,(2)我们使用同步时,要避免出现死锁。
1.死锁的理解:不同的线程分别占用对方需要的同步资源不放弃,都在等待对方放弃自己需要的同步资源,就形成了线程的死锁
2.说明:(1)出现死锁后,不会出现异常,不会出现提示,只是所有的线程都处于阻塞状态,无法继续,(2)我们使用同步时,要避免出现死锁。
五、线程的通信
线程通信的例子:使用两个线程打印1-100。线程1,线程2交替打印,
涉及到的三个方法:
wait():一旦执行此方法,当前线程就进入阻塞状态,并释放同步监视器。
notify():一旦执行此方法,就会唤醒被wait的一个线程。如果有多个线程被wait,就唤醒优先级。
notifyAll():一旦执行此方法,就会唤醒所有被wait的线程。
说明:
1. wait(),notify(),notifyAll()三个方法必须使用在同步代码块或同步方法中。
2. wait(),notify(),notifyAll()三个方法的调用者必须是同步代码块或同步方法中的同步监视器,否则,会出现 IllegalMonitorStateException 异常
3. wait(),notify(),not ifyAll()三个方法是定义在java. lang.Object
class Clerk{
private int productCount = 0;
//生产产品
public synchronized void produceProduct() {
if (productCount < 20){
productCount++;
System.out.println(Thread.currentThread().getName() + ":开始生产第" + productCount + "个产品");
notify();
}else {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//消费产品
public synchronized void consumeProduct() {
if (productCount > 0){
System.out.println(Thread.currentThread().getName() + ":开始消费第" + productCount + "个产品");
productCount--;
notify();
}else{
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Producer extends Thread{
private Clerk clerk;
public Producer(Clerk clerk) {
this.clerk = clerk;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + ":开始生产产品......");
while (true){
try {
sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
clerk.produceProduct();
}
}
}
class Consumer extends Thread{
private Clerk clerk;
public Consumer(Clerk clerk){
this.clerk = clerk;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + ":开始消费产品......");
while (true){
try {
sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
clerk.consumeProduct();
}
}
}
public class ProductTest {
public static void main(String[] args) {
Clerk clerk = new Clerk();
Producer p1 =new Producer(clerk);
p1.setName("生产者1");
Consumer c1 = new Consumer(clerk);
c1.setName("消费者1");
p1.start();
c1.start();
}
}
线程通信的例子:使用两个线程打印1-100。线程1,线程2交替打印,
涉及到的三个方法:
wait():一旦执行此方法,当前线程就进入阻塞状态,并释放同步监视器。
notify():一旦执行此方法,就会唤醒被wait的一个线程。如果有多个线程被wait,就唤醒优先级。
notifyAll():一旦执行此方法,就会唤醒所有被wait的线程。
说明:
1. wait(),notify(),notifyAll()三个方法必须使用在同步代码块或同步方法中。
2. wait(),notify(),notifyAll()三个方法的调用者必须是同步代码块或同步方法中的同步监视器,否则,会出现 IllegalMonitorStateException 异常
3. wait(),notify(),not ifyAll()三个方法是定义在java. lang.Object
最后
附上我的学习视频:尚硅谷Java入门视频教程(在线答疑+Java面试真题)
本文只是博主的一点点Java学习笔记,往后可能会继续更新,谢谢大家的浏览支持!



