本文灵感来自于优锐课java学习笔记,讨论了关于Java Thread概念的简要介绍,很多人觉得很棘手。get了很多干货分享给大家学习参考。
1.什么是Java线程?
2. Java线程模型
3. Java多线程
4. Java主线程
5.如何创建Java线程?
·1.下载最后的股价
·2.检查价格以获取警告
·3.分析特定公司的历史数据
什么是Java线程?
Java线程模型
Java运行时系统在很多方面都依赖于线程。 线程通过防止浪费CPU周期来降低效率。
· 运行-Java线程处于运行状态。
· 已暂停-可以暂停正在运行的线程,这将暂时暂停其活动。 然后可以恢复被挂起的线程,使它可以从中断的位置继续。
· 阻止-等待资源时可以阻止Java线程。
· 终止-线程可以终止,这可以在任何给定时间立即停止执行。 线程终止后,将无法恢复。
Java中的多线程:线程类和可运行接口
Java的多线程系统建立在Thread类,其方法及其配套接口Runnable的基础上。 要创建一个新线程,你的程序将扩展Thread或实现Runnableinterface。hread类定义了几种有助于管理线程的方法:
Method | Meaning |
getName | Obtain thread’s name |
getPriority | Obtain thread’s priority |
isAlive | Determine if a thread is still running |
join | Wait for a thread to terminate |
run | Entry point for the thread |
sleep | Suspend a thread for a period of time |
start | Start a thread by calling its run method |
Java主线程M
为什么主线程如此重要?
·因为它影响其他“子”线程。
·因为它执行各种关闭操作。
·因为它是在程序启动时自动创建的。
如何创建Java线程
Java使你可以通过以下两种方式之一创建线程:
·通过实现Runnable接口。
·通过扩展线程。
·让我们看一下这两种方式如何帮助实现Java线程。
可运行的界面
为了实现Runnable接口,一个类仅需要实现一个名为run()的方法,该方法的声明如下:
public void run( )在run()内部,我们将定义构成新线程的代码。 例:
public class MyClass implements Runnable {public void run(){System.out.println("MyClass running");}}
Thread t1 = new Thread(new MyClass ());t1.start();
扩展Java线程
public class MyClass extends Thread {public void run(){System.out.println("MyClass running");}}
MyClass t1 = new MyClass ();T1.start();
创建多个线程
class MyThread implements Runnable {String name;Thread t;MyThread String thread){name = threadname;t = new Thread(this, name);System.out.println("New thread: " + t);t.start();}public void run() {try {for(int i = 5; i > 0; i--) {System.out.println(name + ": " + i);Thread.sleep(1000);}}catch (InterruptedException e) {System.out.println(name + "Interrupted");}System.out.println(name + " exiting.");}}class MultiThread {public static void main(String args[]) {new MyThread("One");new MyThread("Two");new NewThread("Three");try {Thread.sleep(10000);} catch (InterruptedException e) {System.out.println("Main thread Interrupted");}System.out.println("Main thread exiting.");}}
New thread: Thread[One,5,main]New thread: Thread[Two,5,main]New thread: Thread[Three,5,main]One: 5Two: 5Three: 5One: 4Two: 4Three: 4One: 3Three: 3Two: 3One: 2Three: 2Two: 2One: 1Three: 1Two: 1One exiting.Two exiting.Three exiting.Main thread exiting.
抽丝剥茧,一起来细说架构那些事!