Java 线程基本知识

线程 线程和进程

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

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

线程是程序执行流的最小单

实现线程 继承Thread类并且重写run方法

启动线程的时候需要使用的方法是start() 不能直接调用run()方法

主要方法

- start() 启动线程 - Thread.currentThread() 获取当前线程 - getName() 获取线程名字 - Thread.sleep(long m) 让当前线程停止m毫秒

示例

public class ThreadDemo extends Thread { public static void main(String[] args) { ThreadDemo demo = new ThreadDemo(); demo.start(); // 需要启用start() 并不是直接调用run方法 for (int i = 0; i < 5000; i++) { System.out.println("you are ok"); } } @Override public void run() { for (int i = 0; i < 5000; i++) { System.out.println("张含笑最美"); } } } 实现Runnable接口,并且实现run()方法

Runnable接口中只设定了一个run()方法,所以要启用线程需要new 一个Thread 然后再其构造方法内传递Runnable

因为单继承多实现的原则,避免了单继承的局限性,继承接口的实现了线程对象和线程任务的分离,有利于解耦

示例

``` public class RunnableDemo implements Runnable { public static void main(String[] args) { RunnableDemo demo = new RunnableDemo(); Thread th = new Thread(demo); th.start(); } @Override public void run() { for (int i = 1; i < 2000; i++) { System.out.println(1); } } } ``` 匿名内部类

示例

``` new Thread(){ public void run(){ System.out.println("run1"); } }.start(); new Thread(new Runnable() { @Override public void run() { System.out.println("run2"); } }).start(); ```

本文永久更新链接地址

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/df0c518c8223c86ac45e21de921c37ca.html