线程及创建线程的三种方法

基本概念

程序:是为了完成特定任务,用某种语言编写的一组指令的集合.即指一段静态代码。

进程:进程是程序的一次执行过程,是系统进行资源分配和处理机调度的一个独立单位。

程序是一个静态的概念,进程是一个动态的概念。一个程序多次执行,对应多个进程;不同的进程可以包含同一程序。

线程:进程可进一步细化为线程,是一个程序内部的一条执行路径

在Java中弱化进程的概念,使用的是线程概念。

多个线程在内存模型中共有的区域:方法区、堆

多个线程私有的区域:虚拟机栈、本地方法栈、程序计数器

Java创建线程的三种方法:

Thread是一个类

实现了Runnable接口,其作用为实现多线程

Runnable是一个接口,包含一个run()方法

1,通过继承的方式创建

class My_Thread extends Thread{
	public void run() {
		System.out.println(Thread.currentThread().getName()+"启动");
	}
}
public class Test4 {
	public static void main(String[] args) {
		My_Thread thread1 = new My_Thread();
		My_Thread thread2 = new My_Thread();
		/**
		 * 启动线程1 调用线程的start(),启动此线程,调用相应的run()方法
		 */
		thread1.start();
		/**
		 * 启动线程2 一个线程只能够执行一次start()
		 */
		thread2.start();
	}
}

2,通过接口的方式创建

class My_Thread1 implements Runnable {

	@Override
	public void run() {
		// TODO Auto-generated method stub
		System.out.println(Thread.currentThread().getName()+"启动");
	}
	
}
public class Test4 {
	public static void main(String[] args) {
		My_Thread1 my_Thread1 = new My_Thread1();
		/**
		 * 创建线程
		 */
		Thread thread = new Thread(my_Thread1);
		Thread thread2 = new Thread(my_Thread1);
		/**
		 * 启动线程
		 */
		thread.start();
		thread2.start();
	}
}

3,使用匿名内部类创建

public class Test4 {
	public static void main(String[] args) {
		Thread thread = new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				System.out.println(Thread.currentThread().getName()+"启动");
			}
		});
		
	}
}

Thread与Runable 的区别

Thread 和 Runnable 的相同点:都是“多线程的实现方式”。
Thread 和 Runnable 的不同点
Thread 是类,而Runnable是接口;Thread本身是实现了Runnable接口的类。Runnable具有更好的扩展性。
Runnable还可以用于“资源的共享”。即,多个线程都是基于某一个Runnable对象建立的,它们会共享Runnable对象上的资源。
 

猜你喜欢

转载自blog.csdn.net/qq_37937537/article/details/82759261