Java—多线程

一、多线程

微信图片_20191209174139.png

  • 原理:

    一个cpu内核有”一个指针“,由于cpu的频率过高,所以感觉不到卡顿。(伪线程

二、进程&线程

进程:进程指正在运行的程序。确切的来说,当一个程序进入内存运行,即变成一个进程,进程是处于运行过程中的程序,并且具有一定独立功能。


线程:线程是进程中的一个执行单元,负责当前进程中程序的执行,一个进程中至少有一个线程。一个进程中是可以有多个线程的,这个应用程序也可以称之为多线程程序。

简而言之:一个程序运行后至少有一个进程,一个进程中可以包含多个线程


多线程:多条线程并发执行,分为硬件和软件。

线程是压榨cpu的核心资源;核心数越多,效率越高(线程不提高速度)

进程是压榨cpu的主频;主频越高,效率越高
(伪多线程)(一个CPU内核有一个指针,该指针通过不断变换频率指向不同的代码模块/软件)


三、Thread的子类 & 实现Runnable接口

public class ThreadDemo {
	public static void main(String[] args) throws Exception {
		//Thread
		//Runnable 
		//Thread 实现多线程案例
//		MyThread th1 = new MyThread();//线程1
//		MyThread th2 = new MyThread();//线程2
//		th1.start();
//		th2.start();
//		th1.join();//等待线程一执行结束
//		th2.join();//等待线程二执行结束
//		//主线程执行
//		System.out.println(MyThread.end - MyThread.start);//1
		
		//Runable 实现多线程的案例
		Runnable run = new Runnable() {
			public int i = 100;
			@Override
			public void run() {
				while (i > 0) {
					System.out.println(Thread.currentThread().getName() + " = hello world! " + i );
					i --;
				}
			}
		};
		Thread th1 = new Thread(run);
		Thread th2 = new Thread(run);
		th1.start();
		th2.start();
		
	}
//	public static int i = 1000000;
//	public static void main(String[] args) {
//		//5138
//		long start = System.currentTimeMillis();
//		while (i > 0) {
//			System.out.println(Thread.currentThread().getName() + " = hello world! " + i );
//			i --;
//		}
//		long end = System.currentTimeMillis();
//		System.out.println(end - start);//1
//	}
}


//使用Thread类实现多线程
class MyThread extends Thread{
	public static int i = 1000000;
	public static long start;
	public static long end;
	@Override
	public void run() {
		if(start == 0) {
			start = System.currentTimeMillis();
		}
		while (i > 0) {
			System.out.println(Thread.currentThread().getName() + " = hello world! " + i );
			i --;
		}
		if(end == 0) {
			end = System.currentTimeMillis();
		}
	}
	
}

四、程序运行原理

  • 分时调度

    所有线程轮流使用 CPU 的使用权,平均分配每个线程占用 CPU 的时间。
  • 抢占式调度

    优先让优先级高的线程使用 CPU,如果线程的优先级相同,那么会随机选择一个(线程随机性),Java使用的为抢占式调度。

五、多线程的内存详解

多线程执行时,在栈内存中,其实每一个执行线程都有一片自己所属的栈内存空间。进行方法的压栈和弹栈。

360截图20191209191439344.jpg

原文地址:https://www.cnblogs.com/nadou/p/13983990.html