java多线程
1.基本概念
程序:为完成特定的任务、用某种语言编写的一组指令的集合。
进程:是程序的一次执行过程,或是正在运行的一个程序。
线程:进程可进一步细化为线程,是一个程序内部的一条执行路径。
- 线程作为调度和执行的单位,每个线程拥有独立的运行栈和程序计数器。
- 一个进程的多个线程共享相同的内存单元,内存地址空间
单核CPU和多核CPU的理解
单核CPU,其实是一种假的多线程,因为在一个时间单元内,也只能执行一个线程的任务。例如:虽然有多车道,但是收费站只有一个工作人员在收费,只有收了费才能通过,那么CPU就好比收费人员。如果有某个人不想交钱,那么收费人员可以把他“挂起”(晾着他,等他想通了,准备好了钱,再去收费)。但是因为CPU时间单元特别短,因此感觉不出来。
如果是多核的话,才能更好的发挥多线程的效率。(现在的服务器都是多核的)
一个Java应用程序java.exe,其实至少有三个线程: main()主线程,gc()垃圾回收线程,异常处理线程。当然如果发生异常,会影响主线程。
并行:多个CPU同时执行多个任务。
并发:一个CPU同时执行多个任务。
多线程程序的优点:
- 提高应用程序的响应。对图形化界面更有意义,可增强用户体验。
- 提高计算机系统CPU的利用率
- 改善程序结构。将既长又复杂的进程分为多个线程,独立运行,利于理解和修改
2.多线程的创建和使用
继承于Thread类
//1.创建一个继承于Thread类的子类
class MyThread extends Thread{
//2.重写Thread类的run()
@Override
public void run() {
for(int i = 0;i<100;i++){
if(i%2==0){
System.out.println(i);
}
}
}
}
public class ThreadText {
public static void main(String[] args) {
//3.创建Thread类的子类的对象
MyThread myThread = new MyThread();//快捷键:AlT+Enter 造对象
//4.通过此对象调用start(),1启动当前线程 2.调用当前线程的run()
myThread.start();
//问题一:我们不能通过直接调用run()的方式启动线程
//myThread.run;
//问题二:再启动一个线程,遍历100以内的偶数,不可以还让已经start()的线程去执行。我们需要重新创建一个线程的对象
//mmyThread.start();
MyThread myThread1 = new MyThread();
myThread1.start();
}
}
线程调度策略
- 时间片
- 抢占式:高优先级的线程抢占CPU
Java的调度方法
- 同优先级线程组成先进先出队列(先到先服务),使用时间片策略
- 对高优先级,使用优先调度的抢占式策略
线程的优先级
线程的优先级等级
MAX_PRIORITY:10
MIN_PRIORITY:1
NORM_PRIORITY:5
如何获取和设置当前线程的优先级:
getPriority()∶获取线程的优先级
setPriority (int p):设置线程的优先级
说明:高优先级的线程要抢占低优先级线程cpu的执行权。但是只是从概率上讲,高优先级的线程高概率的情况下被执行。并不意味着只有当高优先级的线程执行完以后,低优先级的线程才执行。
实现Runnable接口
//1.创建一个实现了Runnable接口的类
class MyThread 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 ThreadText {
public static void main(String[] args) {
//3.创建实现类的对象
MyThread myThread = new MyThread();
//4.将此对象作为参数传递到Thread类的构造器种,创建Thread类的对象
Thread thread1 = new Thread(myThread);
//5.通过Thread类的对象调用start()
thread1.start();
//再创一个线程
Thread thread2 = new Thread(myThread);
thread2.start();
}
}
我们调的是Thread的run方法,为何会变为实现Runnable接口重写的run方法?
IDEA中查看当前类所有的方法快捷键:ctrl+F12
private Runnable target;
@Override
public void run() {
if (target != null) {
target.run();
}
}
public Thread(Runnable target) {
init(null, target, "Thread-" + nextThreadNum(), 0);
}
3.线程的生命周期
public enum State {
NEW,
RUNNABLE,
BLOCKED,
WAITING,
TIMED_WAITING,
TERMINATED;
}
4.线程的同步
多个线程对账本的共享,会造成操作的不完整性,会破坏数据。
下面以买票举例:
public class WindowTest implements Runnable{
private int ticket = 100;
@Override
public void run() {
while (true){
if (ticket>0){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println(Thread.currentThread().getName()+"票号为:"+ticket);
ticket--;
}else{
break;
}
}
}
}
class Window{
public static void main(String[] args) {
WindowTest windowTest = new WindowTest();
Thread t1 = new Thread(windowTest);
Thread t2 = new Thread(windowTest);
Thread t3 = new Thread(windowTest);
t1.setName("Window 1");
t2.setName("Window 2");
t3.setName("Window 3");
t1.start();
t2.start();
t3.start();
}
}
原因:当某个线程操作车票的过程中,尚未操作完成时,其他线程参与进来,也操作车票。
在Java中,我们通过同步机制,来解决线程的安全问题。
方式一:同步代码块
-
在实现Runnable接口创建多线程的方式中,可以考虑使用this充当同步监视器。
-
在实现继承Thread创建多线程的方式中,可以考虑使用当前类充当同步监视器。
synchronized(同步监视器){
//需要被同步的代码
}
//说明:操作共享数据的代码,即为需要被同步的代码.共享数据:士多个线程共同操作的变量。比如: ticket就是共享数据。
同步监视器,俗称:锁。任何一个类的对象,都可以充当锁。要求:多个线程必须要共用同一把锁。
public class WindowTest implements Runnable{
private int ticket = 100;
//Object obj = new Object();
@Override
public void run() {
while (true){
// Object obj = new Object(); 多个线程必须要共用同一把锁。
//synchronized (obj)
// synchronized (this) 但有多个WindowTest对象时,会报错
synchronized (WindowTest.class){
if (ticket>0){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println(Thread.currentThread().getName()+"票号为:"+ticket);
ticket--;
}else{
break;
}
}
}
}
}
方式二:同步方法
- 同步方法任然涉及到同步监视器,只是不需要我们显示的申明。
- 非静态的同步方法,同步监视器是:this.
- 静态的同步方法,同步监视器是:当前类本身。
public class WindowTest2 implements Runnable{
private int ticket = 100;
@Override
public void run() {
while (true){
show();
}
}
public synchronized void show(){ //此时:同步监视器:this
if (ticket>0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println(Thread.currentThread().getName() + "票号为:" + ticket);
ticket--;
}
}
}
class Window2{
public static void main(String[] args) {
WindowTest2 windowTest = new WindowTest2();
Thread t1 = new Thread(windowTest);
Thread t2 = new Thread(windowTest);
Thread t3 = new Thread(windowTest);
t1.setName("Window 1");
t2.setName("Window 2");
t3.setName("Window 3");
t1.start();
t2.start();
t3.start();
}
}
线程的死锁问题
什么是死锁?
不同的线程分别占用对方需要的同步资源不放弃,都在等待对方放弃自己需要的同步资源,就形成了线程的死锁。
public class ThreadText {
public static void main(String[] args) {
StringBuffer s1 = new StringBuffer();
StringBuffer s2 = new StringBuffer();
new Thread(){
@Override
public void run() {
synchronized (s1){
s1.append('a');
s2.append(1);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
synchronized (s2){
s1.append('b');
s2.append(2);
System.out.println(s1);
System.out.println(s2);
}
}
}
}.start();
new Thread(new Runnable() {
@Override
public void run() {
synchronized (s2){
s1.append('c');
s2.append(3);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
synchronized (s1){
s1.append('d');
s2.append(4);
System.out.println(s1);
System.out.println(s2);
}
}
}
}).start();
}
}
方式三:Lock锁
public class WindowTest implements Runnable{
private int ticket = 100;
//1. 实例化ReentrantLock
ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
while (true){
try{
//2. 调用lock
lock.lock();
if (ticket>0){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println(Thread.currentThread().getName()+"票号为:"+ticket);
ticket--;
}else{
break;
}
}finally{
lock.unlock();//3. 解锁
}
}
}
}
class Window{
public static void main(String[] args) {
WindowTest windowTest = new WindowTest();
Thread t1 = new Thread(windowTest);
Thread t2 = new Thread(windowTest);
Thread t3 = new Thread(windowTest);
t1.setName("Window 1");
t2.setName("Window 2");
t3.setName("Window 3");
t1.start();
t2.start();
t3.start();
}
}
5.线程的通信
wait( ) ,notify(),notifyALL()三个方法必须使用在同步代码块或同步方法中。
wait(), notify(), notifyAll()三个方法是定义在java.leng.0bject类中。
class Number implements Runnable {
private int number =1;
//方式1 使用公平锁
// ReentrantLock lock = new ReentrantLock(true);
@Override
public void run() {
while (true){
synchronized (this){
if (number<=100){
//方式2
notify();//唤醒。一旦执行此方法,就会唤醒被wait的一个线程。如果有多个线程被wait,就唤醒优先级高的那个。
// notifyAll(); 一旦执行此方法,就会唤醒所有被wait的线程。
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println(Thread.currentThread().getName()+"——>"+number);
number++;
try {
wait();//等待,线程进入阻塞状态,并释放同步监视器
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}else {
break;
}
}
}
}
}
public class CommunicationTest{
public static void main(String[] args) {
Number n1 = new Number();
Number n2 = new Number();
Thread t1 = new Thread(n1);
t1.setName("Thread1");
t1.start();
Thread t2 = new Thread(n1);
t2.setName("Thread2");
t2.start();
}
}
线程通信的例子:使用两个线程打印1-100。线程1,线程2交替打印
面试题: sleep()和wait()的异同?
相同点:一旦执行方法,都可以使得当前的线程进入阻塞状态。
不同点:
1)两个方法声明的位置不同: Thread类中声明sleep() , object类中声明wait().
2)调用的要求不同: sleep()可以在任何需要的场景下调用。wait()必须使用在同步代码块或同步方法中
3)关于是否释放同步监视器:,如果两个方法都使用在同步代码块或同步方法中,sLeep()不会释放同步监视器,而wait()会释放同步监视器
6.JDK5.0新增线程船舰方式
实现Callable接口
class NumThread 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;
}
}
public class ThreadTest{
public static void main(String[] args) {
NumThread numThread = new NumThread();
FutureTask futureTask = new FutureTask(numThread);
//get()返回值即为FutureTask构造器参数callable实现类重写的call()的返回值。
new Thread(futureTask).start();
try {
System.out.println(futureTask.get());
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
}
}
Callable的强大之处:
- caLL()可以有返回值的。
- caLL()可以抛出异常,被外面的操作捕获,获取异常的信息
- callable是支持泛型的
线程池
经常创建和销毁、使用量特别大的资源,比如并发情况下的线程,对性能影响很大。
提前创建好多个线程,放入线程池中,使用时直接获取,使用完放回池中。可以避免频繁创建销毁、实现重复利用。
class NumberTest 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 executorService = Executors.newFixedThreadPool(12);
// 2. 执行线程操作
executorService.execute(new NumberTest());
// executorService.submit();
// 3. 关闭线程池
executorService.shutdown();
}
}