日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 >

Java编程基础25——多线程上

發(fā)布時間:2025/3/19 21 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Java编程基础25——多线程上 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

1_多線程的引入(了解)

  • 1.什么是線程

    • 線程是程序執(zhí)行的一條路徑, 一個進程中可以包含多條線程
    • 多線程并發(fā)執(zhí)行可以提高程序的效率, 可以同時完成多項工作
  • 2.多線程的應(yīng)用場景

    • 紅蜘蛛同時共享屏幕給多個電腦
    • 迅雷開啟多條線程一起下載
    • QQ同時和多個人一起視頻
    • 服務(wù)器同時處理多個客戶端請求

2_多線程并行和并發(fā)的區(qū)別(了解)

  • 并行就是兩個任務(wù)同時運行,就是甲任務(wù)進行的同時,乙任務(wù)也在進行。(需要多核CPU)
  • 并發(fā)是指兩個任務(wù)都請求運行,而處理器只能按受一個任務(wù),就把這兩個任務(wù)安排輪流進行,由于時間間隔較短,使人感覺兩個任務(wù)都在運行。
  • 比如我跟兩個網(wǎng)友聊天,左手操作一個電腦跟甲聊,同時右手用另一臺電腦跟乙聊天,這就叫并行。
  • 如果用一臺電腦我先給甲發(fā)個消息,然后立刻再給乙發(fā)消息,然后再跟甲聊,再跟乙聊。這就叫并發(fā)。

3_Java程序運行原理和JVM的啟動是多線程的嗎(了解)

  • A:Java程序運行原理

    • Java命令會啟動java虛擬機,啟動JVM,等于啟動了一個應(yīng)用程序,也就是啟動了一個進程。該進程會自動啟動一個 “主線程” ,然后主線程去調(diào)用某個類的 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("我是主線程的執(zhí)行代碼");}} } class Demo {public void finalize() {System.out.println("垃圾被清掃了");} }

4_多線程程序?qū)崿F(xiàn)的方式1 *

  • 1.繼承Thread

    • 定義類繼承Thread
    • 重寫run方法
    • 把新線程要做的事寫在run方法中
    • 創(chuàng)建線程對象
    • 開啟新線程, 內(nèi)部會自動執(zhí)行run方法
public class Demo2_Thread {public static void main(String[] args) {MyThread mt = new MyThread(); //4.創(chuàng)建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.將要執(zhí)行的代碼卸載run方法中System.out.println("all");}} }

5_多線程程序?qū)崿F(xiàn)的方式2 *

  • 2.實現(xiàn)Runnable

    • 定義類實現(xiàn)Runnable接口
    • 實現(xiàn)run方法
    • 把新線程要做的事寫在run方法中
    • 創(chuàng)建自定義的Runnable的子類對象
    • 創(chuàng)建Thread對象, 傳入Runnable
    • 調(diào)用start()開啟新線程, 內(nèi)部會自動調(diào)用Runnable的run()方法
public class Demo3_Thread {public static void main(String[] args) {MyRunnable mr = new MyRunnable(); //4.創(chuàng)建MyRunnable的子類對象//Runnable target = mr;Thread t = new Thread(mr); //5.將其當(dāng)做參數(shù)傳遞給Thread的構(gòu)造函數(shù)t.start(); //6.開啟線程for(int i = 0; i < 1000; i++) {System.out.println("idea"); }} }class MyRunnable implements Runnable { //1.定義一個類實現(xiàn)Runnable@Overridepublic void run() { //2.重寫run方法for(int i = 0; i < 1000; i++ ) { //3.將要執(zhí)行的代碼卸載run方法中System.out.println("all");}} }

6_多線程(實現(xiàn)Runnable的原理)(了解)

  • 查看源碼

    • 1,看Thread類的構(gòu)造函數(shù),傳遞了Runnable接口的引用
    • 2,通過init()方法找到傳遞的target給成員變量的target賦值
    • 3,查看run方法,發(fā)現(xiàn)run方法中有判斷,如果target不為null就會調(diào)用Runnable接口子類對象的run方法

7_多線程(兩種方式的區(qū)別)*

  • 查看源碼的區(qū)別:

    • a.繼承Thread : 由于子類重寫了Thread類的run(), 當(dāng)調(diào)用start()時, 直接找子類的run()方法
    • b.實現(xiàn)Runnable : 構(gòu)造函數(shù)中傳入了Runnable的引用, 成員變量記住了它, start()調(diào)用run()方法時內(nèi)部判斷成員變量Runnable的引用是否為空, 不為空編譯時看的是Runnable的run(),運行時執(zhí)行的是子類的run()方法
  • 繼承Thread

    • 好處是:可以直接使用Thread類中的方法,代碼簡單
    • 弊端是:如果已經(jīng)有了父類,就不能用這種方法
  • 實現(xiàn)Runnable接口

    • 好處是:即使自己定義的線程類有了父類也沒關(guān)系,因為有了父類也可以實現(xiàn)接口,而且接口是可以多實現(xiàn)的
    • 弊端是:不能直接使用Thread中的方法需要先獲取到線程對象后,才能得到Thread的方法,代碼復(fù)雜

8_多線程(匿名內(nèi)部類實現(xiàn)線程的兩種方式)*

  • 繼承Thread類
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.將要執(zhí)行的代碼寫在run方法中System.out.println("all");}}}.start(); //4.開啟線程new Thread(new Runnable() { //1.將Runnable子類對象傳遞給Thread的構(gòu)造方法public void run () { //2.重寫run方法for(int i = 0; i <1000; i++ ) { //3.將要執(zhí)行的代碼寫在run方法中System.out.println("idea");}}}).start(); //4.開啟線程} }

9_多線程(獲取名字和設(shè)置名字)*

  • 1.獲取名字

    • 通過getName()方法獲取線程對象的名字
  • 2.設(shè)置名字

    • 通過構(gòu)造函數(shù)可以傳入String類型的名字
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)方法可以設(shè)置線程對象的名字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() { //通過構(gòu)造方法給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_多線程(獲取當(dāng)前線程的對象)*

  • 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()獲取當(dāng)前正在執(zhí)行的線程System.out.println(Thread.currentThread().getName() + "....idea");}}).start();Thread.currentThread().setName("主線程"); //設(shè)置主方法線程的引用,并設(shè)置名字System.out.println(Thread.currentThread().getName()); //獲取主方法線程的引用,并獲取名字} }

11_多線程(休眠線程)*

  • Thread.sleep(毫秒,納秒), 控制當(dāng)前線程休眠若干毫秒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(), 設(shè)置一個線程為守護線程, 該線程不會單獨執(zhí)行, 當(dāng)其他非守護線程都執(zhí)行結(jié)束后, 自動退出
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); //當(dāng)傳入為true即設(shè)置為守護線程t1.start();t2.start();} }

13_多線程(加入線程)*

  • join(), 當(dāng)前線程暫停, 等待指定的線程執(zhí)行結(jié)束后, 當(dāng)前線程再繼續(xù)
  • join(int), 可以等待指定的毫秒之后繼續(xù)
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_多線程(禮讓線程)(了解)

  • yield讓出cpu
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_多線程(設(shè)置線程的優(yōu)先級)(了解)

  • setPriority()設(shè)置線程的優(yōu)先級
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); //設(shè)置最大優(yōu)先級 // t2.setPriority(1);t1.setPriority(Thread.MIN_PRIORITY); //設(shè)置最小的線程優(yōu)先級t1.setPriority(Thread.MAX_PRIORITY); //設(shè)置最大的線程優(yōu)先級t1.start();t2.start();} }

16_多線程(同步代碼塊)*

  • 1.什么情況下需要同步

    • 當(dāng)多線程并發(fā), 有多段代碼同時執(zhí)行時, 我們希望某一段代碼執(zhí)行的過程中CPU不要切換到其他線程工作. 這時就需要同步.
    • 如果兩段代碼是同步的, 那么同一時間只能執(zhí)行一段, 在一段代碼沒執(zhí)行結(jié)束之前, 不會執(zhí)行另外一段代碼.
  • 2.同步代碼塊

    • 使用synchronized關(guān)鍵字加上一個鎖對象來定義一段代碼, 這就叫同步代碼塊
    • 多個同步代碼塊如果使用相同的鎖對象, 那么他們就是同步的
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("學(xué)");System.out.print("習(xí)");System.out.print("編");System.out.print("程");System.out.print("\r\n");}} }class Demo{}

17_多線程(同步方法)*

  • 使用synchronized關(guān)鍵字修飾一個方法, 該方法中所有的代碼都是同步的
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();//非靜態(tài)的同步方法的鎖對象是什么?答:費靜態(tài)的同步方法的鎖對象是this//靜態(tài)的同步方法的鎖對象是什么?答:是該類的字節(jié)碼對象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) { //非靜態(tài)的同步方法的鎖 synchronized(Printer2.class) { //靜態(tài)的同步方法的鎖 System.out.print("學(xué)");System.out.print("習(xí)");System.out.print("編");System.out.print("程");System.out.print("\r\n");}} }class Demo2{}

18_多線程(線程安全問題) *

  • 多線程并發(fā)操作同一數(shù)據(jù)時, 就有可能出現(xiàn)線程安全問題
  • 使用同步技術(shù)可以解決這種問題, 把操作數(shù)據(jù)的代碼進行同步, 不要多個線程一起操作
  • 案例:鐵路售票,一共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(); //如果用引用數(shù)據(jù)類型成員變量當(dāng)鎖對象,必須是靜態(tài)的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_多線程(火車站賣票的例子用實現(xiàn)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_多線程(死鎖)(了解)

  • 多線程同步的時候, 如果同步代碼嵌套, 使用相同鎖, 就有可能出現(xiàn)死鎖

    • 盡量不要嵌套使用
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是線程不安全的

總結(jié)

以上是生活随笔為你收集整理的Java编程基础25——多线程上的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。