生活随笔
收集整理的這篇文章主要介紹了
Java编程基础25——多线程上
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1_多線程的引入(了解) 1.什么是線程
線程是程序執行的一條路徑, 一個進程中可以包含多條線程 多線程并發執行可以提高程序的效率, 可以同時完成多項工作 2.多線程的應用場景
紅蜘蛛同時共享屏幕給多個電腦 迅雷開啟多條線程一起下載 QQ同時和多個人一起視頻 服務器同時處理多個客戶端請求 2_多線程并行和并發的區別(了解) 并行就是兩個任務同時運行,就是甲任務進行的同時,乙任務也在進行。(需要多核CPU) 并發是指兩個任務都請求運行,而處理器只能按受一個任務,就把這兩個任務安排輪流進行,由于時間間隔較短,使人感覺兩個任務都在運行。 比如我跟兩個網友聊天,左手操作一個電腦跟甲聊,同時右手用另一臺電腦跟乙聊天,這就叫并行。 如果用一臺電腦我先給甲發個消息,然后立刻再給乙發消息,然后再跟甲聊,再跟乙聊。這就叫并發。 3_Java程序運行原理和JVM的啟動是多線程的嗎(了解) A:Java程序運行原理
Java命令會啟動java虛擬機,啟動JVM,等于啟動了一個應用程序,也就是啟動了一個進程。該進程會自動啟動一個 “主線程” ,然后主線程去調用某個類的 main 方法。 B:JVM的啟動是多線程的嗎
JVM啟動至少啟動了垃圾回收線程和主線程,所以是多線程的。 public class Demo1_Thread {public static void main(String[] args) {for(int i = 0; i < 1000000; i++) {new Demo();}for(int i = 0; i < 1000000; i++) {System.out.println("我是主線程的執行代碼");}}
}
class Demo {public void finalize() {System.out.println("垃圾被清掃了");}
}
4_多線程程序實現的方式1 * 1.繼承Thread
定義類繼承Thread 重寫run方法 把新線程要做的事寫在run方法中 創建線程對象 開啟新線程, 內部會自動執行run方法 public class Demo2_Thread {public static void main(String[] args) {MyThread mt = new MyThread(); //4.創建Thread類的子類對象mt.start(); //5.開啟線程for(int i = 0; i < 1000; i++) {System.out.println("idea"); }}
}
class MyThread extends Thread { //1.繼承Threadpublic void run() { //2.重寫run方法for(int i = 0; i < 1000; i++ ) {//3.將要執行的代碼卸載run方法中System.out.println("all");}}
}
5_多線程程序實現的方式2 * 2.實現Runnable
定義類實現Runnable接口 實現run方法 把新線程要做的事寫在run方法中 創建自定義的Runnable的子類對象 創建Thread對象, 傳入Runnable 調用start()開啟新線程, 內部會自動調用Runnable的run()方法 public class Demo3_Thread {public static void main(String[] args) {MyRunnable mr = new MyRunnable(); //4.創建MyRunnable的子類對象//Runnable target = mr;Thread t = new Thread(mr); //5.將其當做參數傳遞給Thread的構造函數t.start(); //6.開啟線程for(int i = 0; i < 1000; i++) {System.out.println("idea"); }}
}class MyRunnable implements Runnable { //1.定義一個類實現Runnable@Overridepublic void run() { //2.重寫run方法for(int i = 0; i < 1000; i++ ) { //3.將要執行的代碼卸載run方法中System.out.println("all");}}
}
6_多線程(實現Runnable的原理)(了解) 查看源碼
1,看Thread類的構造函數,傳遞了Runnable接口的引用 2,通過init()方法找到傳遞的target給成員變量的target賦值 3,查看run方法,發現run方法中有判斷,如果target不為null就會調用Runnable接口子類對象的run方法 7_多線程(兩種方式的區別)* 查看源碼的區別:
a.繼承Thread : 由于子類重寫了Thread類的run(), 當調用start()時, 直接找子類的run()方法 b.實現Runnable : 構造函數中傳入了Runnable的引用, 成員變量記住了它, start()調用run()方法時內部判斷成員變量Runnable的引用是否為空, 不為空編譯時看的是Runnable的run(),運行時執行的是子類的run()方法 繼承Thread
好處是:可以直接使用Thread類中的方法,代碼簡單 弊端是:如果已經有了父類,就不能用這種方法 實現Runnable接口
好處是:即使自己定義的線程類有了父類也沒關系,因為有了父類也可以實現接口,而且接口是可以多實現的 弊端是:不能直接使用Thread中的方法需要先獲取到線程對象后,才能得到Thread的方法,代碼復雜 8_多線程(匿名內部類實現線程的兩種方式)* public class Demo4_Thread {public static void main(String[] args) {new Thread() { //1.繼承Thread類public void run () { //2.重寫run方法for(int i = 0; i <1000; i++ ) { //3.將要執行的代碼寫在run方法中System.out.println("all");}}}.start(); //4.開啟線程new Thread(new Runnable() { //1.將Runnable子類對象傳遞給Thread的構造方法public void run () { //2.重寫run方法for(int i = 0; i <1000; i++ ) { //3.將要執行的代碼寫在run方法中System.out.println("idea");}}}).start(); //4.開啟線程}
}
9_多線程(獲取名字和設置名字)* public class Demo1_Name {public static void main(String[] args) {
// demo1();
// demo2();Thread t1 = new Thread() {public void run() {System.out.println(this.getName() + "_____all");}};Thread t2 = new Thread() {public void run() {System.out.println(this.getName() + "_____idea");}};t1.setName("張三");t1.start();t2.setName("李四");t2.start();}private static void demo2() { //通過setName(String)方法可以設置線程對象的名字new Thread() {public void run() {this.setName("所有");System.out.println(this.getName() + "_____all");}}.start();new Thread() {public void run() {this.setName("全部");System.out.println(this.getName() + "_____idea");}}.start();}private static void demo1() { //通過構造方法給name賦值new Thread("name-1") {public void run() {System.out.println(this.getName() + "_____all");}}.start();new Thread("name-2") {public void run() {System.out.println(this.getName() + "_____idea");}}.start();}
}
10_多線程(獲取當前線程的對象)* Thread.currentThread(), 主線程也可以獲取 public class Demo2_CurrentThread {public static void main(String[] args) {new Thread() {public void run() {System.out.println(getName() + "....all");}}.start();new Thread(new Runnable() {public void run() {//Thread.currentThread()獲取當前正在執行的線程System.out.println(Thread.currentThread().getName() + "....idea");}}).start();Thread.currentThread().setName("主線程"); //設置主方法線程的引用,并設置名字System.out.println(Thread.currentThread().getName()); //獲取主方法線程的引用,并獲取名字}
}
11_多線程(休眠線程)* Thread.sleep(毫秒,納秒), 控制當前線程休眠若干毫秒1秒= 1000毫秒 1秒 = 1000 1000 1000納秒 1000000000 public class Demo3_sleep {public static void main(String[] args) throws InterruptedException {
// demo1();new Thread() {public void run() {for(int i = 0; i <= 10; i++) {try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(getName() + "____all");}}}.start();new Thread() {public void run() {for(int i = 0; i <= 10; i++) {try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(getName() + "____idea");}}}.start();}private static void demo1() throws InterruptedException {for(int i = 10; i >= 0; i--) {Thread.sleep(1000);System.out.println("倒計時第" + i + "秒");}}
}
12_多線程(守護線程)* setDaemon(), 設置一個線程為守護線程, 該線程不會單獨執行, 當其他非守護線程都執行結束后, 自動退出 public class Demo4_Daemon {public static void main(String[] args) {Thread t1 = new Thread() {public void run() {for(int i = 0; i < 2; i++) {System.out.println(getName() + "____all");}}};Thread t2 = new Thread() {public void run() {for(int i = 0; i < 50; i++) {System.out.println(getName() + "____idea");}}};t2.setDaemon(true); //當傳入為true即設置為守護線程t1.start();t2.start();}
}
13_多線程(加入線程)* join(), 當前線程暫停, 等待指定的線程執行結束后, 當前線程再繼續 join(int), 可以等待指定的毫秒之后繼續 public class Demo5_join {public static void main(String[] args) {final Thread t1 = new Thread() {public void run() {for(int i = 0; i < 10; i++) {System.out.println(getName() + "____all");}}};final Thread t2 = new Thread() {public void run() {for(int i = 0; i < 10; i++) {if(i == 2) {try {//t1.join();t1.join(1); //插隊1毫秒} catch (InterruptedException e) {e.printStackTrace();}}System.out.println(getName() + "____idea");}}};t1.start();t2.start();}
}
14_多線程(禮讓線程)(了解) public class Demo6_Yield {public static void main(String[] args) {new MyThread().start();new MyThread().start();}
}class MyThread extends Thread {public void run() {for(int i = 1; i <= 1000; i++) {if(i % 10 == 0) {Thread.yield(); //讓出cpu}System.out.println(getName() + "...." + i);}}
}
15_多線程(設置線程的優先級)(了解) public class Demo7_Priority {public static void main(String[] args) {Thread t1 = new Thread() {public void run() {for(int i = 0; i < 100; i++) {System.out.println(getName() + "___all");}}};Thread t2 = new Thread() {public void run() {for(int i = 0; i < 100; i++) {System.out.println(getName() + "___idea");}}};// t1.setPriority(10); //設置最大優先級
// t2.setPriority(1);t1.setPriority(Thread.MIN_PRIORITY); //設置最小的線程優先級t1.setPriority(Thread.MAX_PRIORITY); //設置最大的線程優先級t1.start();t2.start();}
}
16_多線程(同步代碼塊)* 1.什么情況下需要同步
當多線程并發, 有多段代碼同時執行時, 我們希望某一段代碼執行的過程中CPU不要切換到其他線程工作. 這時就需要同步. 如果兩段代碼是同步的, 那么同一時間只能執行一段, 在一段代碼沒執行結束之前, 不會執行另外一段代碼. 2.同步代碼塊
使用synchronized關鍵字加上一個鎖對象來定義一段代碼, 這就叫同步代碼塊 多個同步代碼塊如果使用相同的鎖對象, 那么他們就是同步的 public class Demo1_Synchronized {public static void main(String[] args) {final Printer p = new Printer();new Thread() {public void run() {while(true) {p.print1();}}}.start();new Thread() {public void run() {while(true) {p.print2();}}}.start();}
}class Printer {Demo d = new Demo();public void print1() {synchronized(d) { System.out.print("我");System.out.print("愛");System.out.print("寫");System.out.print("代");System.out.print("碼");System.out.print("\r\n");}}public void print2() {
// synchronized(new Demo) { //鎖對象不能用匿名對象,因為不是一個對象synchronized(d) { //同步代碼塊,鎖機制,鎖對象是任意的 System.out.print("學");System.out.print("習");System.out.print("編");System.out.print("程");System.out.print("\r\n");}}
}class Demo{}
17_多線程(同步方法)* 使用synchronized關鍵字修飾一個方法, 該方法中所有的代碼都是同步的 public class Demo2_Synchronized {public static void main(String[] args) {final Printer2 p = new Printer2();new Thread() {public void run() {while(true) {p.print1();}}}.start();new Thread() {public void run() {while(true) {p.print2();}}}.start();}
}class Printer2 {Demo2 d = new Demo2();//非靜態的同步方法的鎖對象是什么?答:費靜態的同步方法的鎖對象是this//靜態的同步方法的鎖對象是什么?答:是該類的字節碼對象public static synchronized void print1() { //同步方法-在方法上加syncronizedSystem.out.print("我");System.out.print("愛");System.out.print("寫");System.out.print("代");System.out.print("碼");System.out.print("\r\n");}public static void print2() {
// synchronized(new Demo) { //鎖對象不能用匿名對象,因為不是一個對象
// synchronized(this) { //非靜態的同步方法的鎖 synchronized(Printer2.class) { //靜態的同步方法的鎖 System.out.print("學");System.out.print("習");System.out.print("編");System.out.print("程");System.out.print("\r\n");}}
}class Demo2{}
18_多線程(線程安全問題) * 多線程并發操作同一數據時, 就有可能出現線程安全問題 使用同步技術可以解決這種問題, 把操作數據的代碼進行同步, 不要多個線程一起操作 案例:鐵路售票,一共100張,通過四個窗口賣完. public class Demo3_Ticket {public static void main(String[] args) {new Ticket().start();new Ticket().start();new Ticket().start();new Ticket().start();}
}class Ticket extends Thread {private static int ticket = 100;
// private static Object obj = new Object(); //如果用引用數據類型成員變量當鎖對象,必須是靜態的public void run() {while(true) {
// synchronized(obj) {synchronized(Ticket.class) {if(ticket == 0) {break;}try {Thread.sleep(10);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(getName() + "這是第" + ticket-- + "號票");}}}
}
19_多線程(火車站賣票的例子用實現Runnable接口) * public class Demo4_Ticket {public static void main(String[] args) {MyTicket mt = new MyTicket();new Thread(mt).start();new Thread(mt).start();new Thread(mt).start();new Thread(mt).start();/*Thread t1 = new Thread(mt); //多次啟動一個線程是非法的t1.start();t1.start();t1.start();t1.start();*/}
}class MyTicket implements Runnable {private int tickets = 1000;@Overridepublic void run() {while(true) {synchronized(this) {if(tickets <= 0) {break;}try {Thread.sleep(10);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(Thread.currentThread().getName() + "這是第" + tickets-- + "號票");}}}
}
20_多線程(死鎖)(了解) public class Demo5_DeadLock {private static String s1 = "筷子1";private static String s2 = "筷子2";public static void main(String[] args) {new Thread() {public void run() {while(true) {synchronized(s1) {System.out.println(getName() + "獲取" + s1 + "等待s2");synchronized(s2) {System.out.println(getName() + "拿到" + s2 + "開吃");}}}}}.start();new Thread() {public void run() {while(true) {synchronized(s2) {System.out.println(getName() + "獲取" + s2 + "等待s2");synchronized(s1) {System.out.println(getName() + "拿到" + s1 + "開吃");}}}}}.start();}
}
21_多線程(以前的線程安全的類回顧) * A:回顧以前說過的線程安全問題
看源碼:Vector,StringBuffer,Hashtable,Collections.synchroinzed(xxx) Vector是線程安全的,ArrayList是線程不安全的 StringBuffer是線程安全的,StringBuilder是線程不安全的 Hashtable是線程安全的,HashMap是線程不安全的
總結
以上是生活随笔 為你收集整理的Java编程基础25——多线程上 的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔 網站內容還不錯,歡迎將生活随笔 推薦給好友。