多執行緒和匿名內部類的理解
多執行緒
一.多執行緒
-
好處:提高任務的執行效率 (執行緒本身也會耗費系統資源 建立執行緒要把握度)
-
程序:一個正在執行的程式 一個程序可以有一個或多個執行緒
分時排程:cpu同一時間只能執行一個任務(cpu單核單執行緒) -
要同時執行多個任務 這時cpu就會為 多個任務開闢多個獨立的執行路徑(執行路徑 執行功能的程式碼)
-
cpu會在多個任務之間進行快速切換
-
搶佔資源:搶奪cpu的執行資源 改變任務的優先順序
-
public class Demo01 {
public static void main(String[] args) {
//建立子執行緒
SubThread st=new SubThread();
//開啟執行緒
st.start();
SubThread st1=new SubThread();
st1.start();
// st.run();
for (int i = 0; i < 100; i++) {
System.out.println(“main----”+i);
}
System.out.println(“main”);
}
}
//建立執行緒類的子類
class SubThread extends Thread{
//重寫run方法
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(“run–”+i);
}
}
}
二.執行緒的命名 -
主執行緒:main
-
子執行緒:預設 Thread-x(x從0開始)
-
public class Demo02 {
public static void main(String[] args) {
NameThread nt1=new NameThread(“吼吼吼吼”);
nt1.start();
NameThread nt2=new NameThread(“酸辣筍尖粉”);
nt2.start();
//列印主執行緒的名字
Thread currentThread = Thread.currentThread();
System.out.println(currentThread.getName());
}
}
class NameThread extends Thread{
//構造方法
public NameThread() {
// TODO Auto-generated constructor stub
}
public NameThread(String string) {
super(string);
}
public void run() {
for (int i = 0; i < 50; i++) {
//獲取執行緒的名字
}}
}
三.執行緒兩種建立方式(實現和繼承)
繼承方式 -
1.增加類和類的耦合度 2.java中類只能單繼承
-
實現方式
-
2.介面可以多實現(靈活) 2.將執行緒要執行的方法 從類中分離出來
-
public class Demo03 {
public static void main(String[] args) {
TestThread t =new TestThread();
t.start();
funmain();
System.out.println(“最後”);
}
public static void funmain() {
for (int i = 0; i < 80; i++) { System.out.println(Thread.currentThread().getName()+“+fun"+i);
}
}
}
class TestThread extends Thread{
public void run() {
for (int i = 0; i < 50; i++) {
//獲取當前執行緒名字 System.out.println(Thread.currentThread().getName()+"
}
fun();
}
public void fun() { System.out.println(Thread.currentThread().getName()+"****+fun");
}
}
public class Demo04 {
public static void main(String[] args) {
//建立介面的實現類物件
Runnablep1 rp=new Runnablep1();
//建立執行緒類物件
Thread t=new Thread(rp);
//開啟執行緒
t.start();
}
}
class Runnablep1 implements Runnable{
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
四.匿名內部類建立子類或實現類物件
public class Demo05 {
public static void main(String[] args) {
//相當於建立了 test類的 子類物件 且沒有類名
Test t=new Test() {
public void fun() {
System.out.println(“重寫Test方法”);
}
};
t.fun();
//建立介面實現類
Inter x=new Inter() {
public void fun() {
System.out.println("實現類fun方法");
}
};
x.fun();
new Inter() {
public void fun() {
System.out.println("hohouhdfjkfi");
}
}.fun();
}
}
class Test{
public void fun() {
System.out.println(“test方法”);
}
}
interface Inter{
public abstract void fun();
}
五.執行緒的6種狀態(新建狀態 執行狀態 受阻塞狀態 等待狀態 休眠狀態 死亡狀態)
沒有得到執行資源的執行緒 會進入 受阻塞狀態
當受阻塞狀態的執行緒 得到執行資源 會進入執行狀態
*
執行狀態–>休眠狀態 相當於 放棄了cpu的執行權
等休眠時間結束 重新獲得cpu 的執行權
*
執行狀態–>等待狀態 相當於 放棄了cpu的執行權
等到呼叫了notify()方法 重新獲得cpu的執行權
![在這裡插入圖片描述](%E5%85%AD%E7%A7