多线程基础(一)
最近讀了高洪巖老師的《Java多線程編程核心技術(shù)》一書,打算記錄下多線程的基礎(chǔ)知識(shí)點(diǎn),也算對(duì)本書的一個(gè)讀后感了。目前打算分四五篇博文進(jìn)行記錄。
第一篇主要是記錄線程的概念,創(chuàng)建,常用的基礎(chǔ)方法等。
1. 什么是線程?
通常我們所說(shuō)線程是進(jìn)程的最小單位。那么問(wèn)題來(lái)了,什么是進(jìn)程呢?進(jìn)程就是操作系統(tǒng)結(jié)構(gòu)的基礎(chǔ);是一次程序的執(zhí)行;等等,他是系統(tǒng)進(jìn)行資源分配和調(diào)度的一個(gè)獨(dú)立單位。
2. 創(chuàng)建線程的4種方式
1、繼承Thread類? 2、實(shí)現(xiàn)Runnable接口? 3、實(shí)現(xiàn)Callable接口重寫call()方法(注:需要搭配Future)? ?4、使用線程池(例:Executor框架)
3. 下面講解線程中的各方法使用
3.1? currentThread()方法
作用:返回代碼段正在被哪個(gè)線程調(diào)用的信息。
示例:
public class CreateThreandA implements Callable {@Overridepublic Object call() throws Exception {System.out.println("run方法:"+Thread.currentThread().getName());return "ok";}public static void main(String[] args) throws ExecutionException, InterruptedException {CreateThreandA threandA = new CreateThreandA();FutureTask futureTask = new FutureTask(threandA);ExecutorService executorService = Executors.newFixedThreadPool(1);executorService.submit(futureTask);executorService.shutdown();System.out.println("mian方法:"+Thread.currentThread().getName());} } //執(zhí)行結(jié)果 mian方法:main run方法:pool-1-thread-13.2? isAlive()方法
作用:判斷當(dāng)前線程是否處于活動(dòng)狀態(tài)(true活動(dòng)狀態(tài)、false線程終止)
示例:?
public class CreateThreandA extends Thread {@Overridepublic void run() {System.out.println("begain···");System.out.println("threandA="+this.isAlive());System.out.println("end···");}public static void main(String[] args) throws InterruptedException {CreateThreandA threandA = new CreateThreandA();threandA.start();threandA.join();System.out.println("threandA="+threandA.isAlive());} } //執(zhí)行結(jié)果 begain··· threandA=true end··· threandA=false3.3? sleep()方法
作用:在指定的毫秒數(shù)內(nèi)讓當(dāng)前正在運(yùn)行的線程休眠(注:不會(huì)釋放鎖)
示例:
public class CreateThreandA extends Thread {private static Logger logger = LoggerFactory.getLogger(CreateThreandA.class);@Overridepublic void run() {System.out.println("begain···"+System.currentTimeMillis());try {Thread.sleep(2000);System.out.println("休眠中···");} catch (InterruptedException e) {e.printStackTrace();}System.out.println("end···"+System.currentTimeMillis());}public static void main(String[] args) throws InterruptedException {CreateThreandA threandA = new CreateThreandA();threandA.start();} } //執(zhí)行結(jié)果(相差2秒) begain···1541213244502 休眠中··· end···15412132465043.4? getId()方法
作用:獲取線程的唯一標(biāo)識(shí)
示例:
public class CreateThreandA extends Thread {private static Logger logger = LoggerFactory.getLogger(CreateThreandA.class);@Overridepublic void run() {}public static void main(String[] args) throws InterruptedException {CreateThreandA threandA = new CreateThreandA();threandA.start();System.out.println(Thread.currentThread().getName()+"--標(biāo)識(shí)="+Thread.currentThread().getId());System.out.println(threandA.getName()+"--標(biāo)識(shí)="+threandA.getId());} } //執(zhí)行結(jié)果 main--標(biāo)識(shí)=1 Thread-0--標(biāo)識(shí)=113.5? interrupted()
作用:測(cè)試當(dāng)前線程是否已經(jīng)中斷(具有清除狀態(tài)的功能)
public class CreateThreandA {public static void main(String[] args) throws InterruptedException {Thread.currentThread().interrupt();System.out.println(Thread.interrupted());System.out.println(Thread.interrupted());//清除了true的狀態(tài)} } //執(zhí)行結(jié)果 true false3.6? isInterrupted()
作用:測(cè)試線程是否已經(jīng)中斷(不會(huì)清楚狀態(tài))
public class CreateThreandA {public static void main(String[] args) throws InterruptedException {System.out.println(Thread.currentThread().isInterrupted());Thread.currentThread().interrupt();System.out.println(Thread.currentThread().isInterrupted());System.out.println(Thread.currentThread().isInterrupted());} } //執(zhí)行結(jié)果 false true true3.7? stop()
作用:暴力停止線程(已經(jīng)廢棄,不推薦使用、所以我也不做示例了)
3.8? suspend()和resume()
作用:suspend()暫停線程;resume()恢復(fù)線程? (注:這兩種也已廢棄,不做示例演示)
3.9? yield()?
作用:放棄當(dāng)前CPU資源,將它讓給其他任務(wù)去占用CPU執(zhí)行時(shí)間
public class CreateThreandA extends Thread {private int count = 0;public void run(){long time1 = System.currentTimeMillis();for (int i=0;i<50000000;i++){Thread.yield();count+=i;}long time2 = System.currentTimeMillis();System.out.println("耗時(shí):"+(time2-time1));}public static void main(String[] args){CreateThreandA threandA = new CreateThreandA();threandA.start();} }3.10? setPriority()
作用:設(shè)置線程的優(yōu)先級(jí)(注:優(yōu)先級(jí)只能是1~10、否則會(huì)報(bào)錯(cuò),線程的優(yōu)先級(jí)仍然無(wú)法保障線程的執(zhí)行次序。只不過(guò),優(yōu)先級(jí)高的線程獲取CPU資源的概率較大,優(yōu)先級(jí)低的并非沒(méi)機(jī)會(huì)執(zhí)行。)
public class CreateThreandA extends Thread {CreateThreandA(String name){super(name);}public void run(){System.out.println(this.getName());}public static void main(String[] args){CreateThreandA threandA = new CreateThreandA("A");CreateThreandA threandB = new CreateThreandA("B");CreateThreandA threandC = new CreateThreandA("C");CreateThreandA threandD = new CreateThreandA("D");threandA.setPriority(1);threandB.setPriority(2);threandC.setPriority(3);threandD.setPriority(10);threandA.start();threandB.start();threandC.start();threandD.start();} }3.11? wait()
作用:線程等待(釋放鎖)
public class CreateThreandA extends Thread {private Object lock;CreateThreandA(String name,Object lock){super(name);this.lock=lock;}public void run(){try {synchronized (lock){System.out.println("上鎖");lock.wait();System.out.println("開鎖");}} catch (InterruptedException e) {e.printStackTrace();}}public static void main(String[] args){Object lock = new Object();CreateThreandA threandA = new CreateThreandA("A",lock);CreateThreandA threandB = new CreateThreandA("B",lock);threandA.start();threandB.start();} } //執(zhí)行結(jié)果 上鎖 上鎖3.12? notify()、notifyAll()
作用:釋放鎖(notify隨機(jī)釋放一個(gè)鎖、notifyAll釋放全部鎖)
開鎖 public class CreateThreandB extends Thread {private Object lock;CreateThreandB(String name, Object lock){super(name);this.lock=lock;}public void run(){try {synchronized (lock){lock.notify();}} catch (Exception e) {e.printStackTrace();}} }上鎖 public class CreateThreandA extends Thread {private Object lock;CreateThreandA(String name,Object lock){super(name);this.lock=lock;}public void run(){try {synchronized (lock){System.out.println("上鎖");lock.wait();System.out.println("開鎖");}} catch (InterruptedException e) {e.printStackTrace();}}public static void main(String[] args){Object lock = new Object();CreateThreandA threandA = new CreateThreandA("A",lock);CreateThreandA threandB = new CreateThreandA("B",lock);CreateThreandB threand = new CreateThreandB("C",lock);threandA.start();threandB.start();threand.start();} } //執(zhí)行結(jié)果(印證隨機(jī)開一個(gè)鎖) 上鎖 開鎖 上鎖notifyAll開全部鎖 修改開鎖類 lock.notifyAll(); //執(zhí)行結(jié)果 上鎖 上鎖 開鎖 開鎖3.13? join()
?作用:等待線程對(duì)象銷毀(如果子線程需要較長(zhǎng)時(shí)間執(zhí)行,主線程往往會(huì)提前執(zhí)行完畢,如果想等待子線程時(shí)可以采用join)
package com.chenpt.thread;import org.omg.Messaging.SYNC_WITH_TRANSPORT;/*** @Author: chen* @Description:* @Date: created in 2018/11/3* @Modified By:*/ public class CreateThreandA extends Thread {private Object lock;CreateThreandA(String name,Object lock){super(name);this.lock=lock;}public void run(){try {System.out.println("休眠");Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}public static void main(String[] args) throws InterruptedException {Object lock = new Object();CreateThreandA threandA = new CreateThreandA("A",lock);threandA.start();threandA.join();System.out.println("我是主線程,我應(yīng)該等等子線程");} } //執(zhí)行結(jié)果 休眠 我是主線程,我應(yīng)該等等子線程 (如果不加join,則主線程先輸出)
先總結(jié)這些基礎(chǔ)方法,下面注重講解進(jìn)階知識(shí)
?
轉(zhuǎn)載于:https://www.cnblogs.com/chenpt/p/9897674.html
總結(jié)
- 上一篇: HTML_盒子模型
- 下一篇: 关于javascript的原型和原型链,