- Java多線程基本使用 推薦度:
- 相關(guān)推薦
Java多線程的基本使用
導(dǎo)語(yǔ):多線程是Java中不可避免的一個(gè)重要主體,今天我們就來(lái)講講它的基本使用,一起來(lái)學(xué)習(xí)下吧:
一、概念
1.進(jìn)程
1.1進(jìn)程:是一個(gè)正在進(jìn)行中的程序,每一個(gè)進(jìn)程執(zhí)行都有一個(gè)執(zhí)行順序,該順序是一個(gè)執(zhí)行路徑,或者叫一個(gè)控制單元。
1.2線程:就是進(jìn)程中一個(gè)獨(dú)立的控制單元,線程在控制著進(jìn)程的執(zhí)行,一個(gè)進(jìn)程中至少有一個(gè)線程。
1.3舉例java VM:
Java VM啟動(dòng)的時(shí)候會(huì)有一個(gè)進(jìn)程java.exe,該進(jìn)程中至少有一個(gè)線程在負(fù)責(zé)java程序的運(yùn)行,而且這個(gè)線程運(yùn)行的代碼存在于main方法中,該線程稱之為主線程。擴(kuò)展:其實(shí)更細(xì)節(jié)說(shuō)明jvm,jvm啟動(dòng)不止一個(gè)線程,還有負(fù)責(zé)垃圾回收機(jī)制的線程
2.多線程存在的意義:提高執(zhí)行效率
二、多線程的創(chuàng)建
1.多線程創(chuàng)建的第一種方式,繼承Thread類(lèi)
1.1定義類(lèi)繼承Thread,復(fù)寫(xiě)Thread類(lèi)中的run方法是為了將自定義的代碼存儲(chǔ)到run方法中,讓線程運(yùn)行
1.2調(diào)用線程的start方法,該方法有兩個(gè)作用:?jiǎn)?dòng)線程,調(diào)用run方法
1.3多線程運(yùn)行的時(shí)候,運(yùn)行結(jié)果每一次都不同,因?yàn)槎鄠(gè)線程都獲取cpu的執(zhí)行權(quán),cpu執(zhí)行到誰(shuí),誰(shuí)就運(yùn)行,明確一點(diǎn),在某一個(gè)時(shí)刻,只能有一個(gè)程序在運(yùn)行。(多核除外),cpu在做著快速的切換,以到達(dá)看上去是同時(shí)運(yùn)行的效果。我們可以形象把多線程的運(yùn)行行為在互搶cpu的執(zhí)行權(quán)。這就是多線程的一個(gè)特性,隨機(jī)性。誰(shuí)搶到,誰(shuí)執(zhí)行,至于執(zhí)行多久,cpu說(shuō)了算。
public class Demo extends Thread{
public void run(){
for (int x = 0; x < 60; x++) {
System.out.println(this.getName()+"demo run---"+x);
}
}
public static void main(String[] args) {
Demo d=new Demo();//創(chuàng)建一個(gè)線程
d.start();//開(kāi)啟線程,并執(zhí)行該線程的run方法
d.run(); //僅僅是對(duì)象調(diào)用方法,而線程創(chuàng)建了但并沒(méi)有運(yùn)行
for (int x = 0; x < 60; x++) {
System.out.println("Hello World---"+x);
}
}
}
2 創(chuàng)建多線程的第二種方式,步驟:
2.1定義類(lèi)實(shí)現(xiàn)Runnable接口
2.2覆蓋Runnable接口中的run方法:將線程要運(yùn)行的代碼存放到run方法中
2.3.通過(guò)Thread類(lèi)建立線程對(duì)象
2.4.將Runnable接口的子類(lèi)對(duì)象作為實(shí)際參數(shù)傳遞給Thread類(lèi)的構(gòu)造函數(shù)
為什么要將Runnable接口的子類(lèi)對(duì)象傳遞給Thread的構(gòu)造函數(shù):因?yàn)樽远x的run方法所屬的對(duì)象是Runnable接口的子類(lèi)對(duì)象,所以要讓線程去執(zhí)行指定對(duì)象的run方法,就必須明確該run方法的所屬對(duì)象
2.5.調(diào)用Thread類(lèi)的start方法開(kāi)啟線程并調(diào)用Runnable接口子類(lèi)的方法
/*
* 需求:簡(jiǎn)易買(mǎi)票程序,多個(gè)窗口同時(shí)賣(mài)票
*/
public class Ticket implements Runnable {
private static int tick = 100;
Object obj = new Object();
boolean flag=true;
public void run() {
if(flag){
while (true) {
synchronized (Ticket.class) {
if (tick > 0) {
System.out.println(Thread.currentThread().getName()
+ "code:" + tick--);
}
}
}
}else{
while(true){
show();
}
}
}
public static synchronized void show() {
if (tick > 0) {
System.out.println(Thread.currentThread().getName() + "show:"
+ tick--);
}
}
}
class ThisLockDemo {
public static void main(String[] args) {
Ticket t = new Ticket();
Thread t1 = new Thread(t);
try {
Thread.sleep(10);
} catch (Exception e) {
// TODO: handle exception
}
t.flag=false;
Thread t2 = new Thread(t);
//Thread t3 = new Thread(t);
//Thread t4 = new Thread(t);
t1.start();
t2.start();
//t3.start();
//t4.start();
}
}
3.實(shí)現(xiàn)方式和繼承方式有什么區(qū)別
3.1.實(shí)現(xiàn)方式避免了單繼承的局限性,在定義線程時(shí)建議使用實(shí)現(xiàn)方式
3.2.繼承Thread類(lèi):線程代碼存放在Thread子類(lèi)run方法中
3.3.實(shí)現(xiàn)Runnable:線程代碼存放在接口的子類(lèi)run方法中
4.多線程-run和start的特點(diǎn)
4.1為什么要覆蓋run方法呢:
Thread類(lèi)用于描述線程,該類(lèi)定義了一個(gè)功能,用于存儲(chǔ)線程要運(yùn)行的代碼,該存儲(chǔ)功能就是run方法,也就是說(shuō)該Thread類(lèi)中的run方法,用于存儲(chǔ)線程要運(yùn)行的代碼
5.多線程運(yùn)行狀態(tài)
創(chuàng)建線程-運(yùn)行---sleep()/wait()--凍結(jié)---notify()---喚醒
創(chuàng)建線程-運(yùn)行---stop()—消亡
創(chuàng)建線程-運(yùn)行---沒(méi)搶到cpu執(zhí)行權(quán)—臨時(shí)凍結(jié)
6.獲取線程對(duì)象及其名稱
6.1.線程都有自己默認(rèn)的名稱,編號(hào)從0開(kāi)始
6.2.static Thread currentThread():獲取當(dāng)前線程對(duì)象
6.3.getName():獲取線程名稱
6.4.設(shè)置線程名稱:setName()或者使用構(gòu)造函數(shù)
public class Test extends Thread{
Test(String name){
super(name);
}
public void run(){
for (int x = 0; x < 60; x++) {
System.out.println((Thread.currentThread()==this)+"..."+this.getName()+" run..."+x);
}
}
}
class ThreadTest{
public static void main(String[] args) {
Test t1=new Test("one---");
Test t2=new Test("two+++");
t1.start();
t2.start();
t1.run();
t2.run();
for (int x = 0; x < 60; x++) {
System.out.println("main----"+x);
}
}
}
三、多線程的安全問(wèn)題
1.多線程出現(xiàn)安全問(wèn)題的原因:
1.1.當(dāng)多條語(yǔ)句在操作同一個(gè)線程共享數(shù)據(jù)時(shí),一個(gè)線程對(duì)多條語(yǔ)句只執(zhí)行了一部分,還沒(méi)有執(zhí)行完,另一個(gè)線程參與進(jìn)來(lái)執(zhí)行,導(dǎo)致共享數(shù)據(jù)的錯(cuò)誤
1.2.解決辦法:對(duì)多條操作共享數(shù)據(jù)的語(yǔ)句,只能讓一個(gè)線程都執(zhí)行完,在執(zhí)行過(guò)程中,其他線程不可以參與執(zhí)行
1.3.java對(duì)于多線程的安全問(wèn)題提供了專業(yè)的解決方式,就是同步代碼塊:
Synchronized(對(duì)象){需要被同步的代碼},對(duì)象如同鎖,持有鎖的線程可以在同步中執(zhí)行,沒(méi)有持有鎖的線程即使獲取cpu執(zhí)行權(quán),也進(jìn)不去,因?yàn)闆](méi)有獲取鎖
2.同步的前提:
2.1.必須要有2個(gè)或者2個(gè)以上線程
2.2.必須是多個(gè)線程使用同一個(gè)鎖
2.3.好處是解決了多線程的安全問(wèn)題
2.4.弊端是多個(gè)線程需要判斷鎖,較消耗資源
2.5.同步函數(shù)
定義同步函數(shù),在方法錢(qián)用synchronized修飾即可
/*
* 需求:
* 銀行有一個(gè)金庫(kù),有兩個(gè)儲(chǔ)戶分別存300元,每次存100元,存3次
* 目的:該程序是否有安全問(wèn)題,如果有,如何解決
* 如何找問(wèn)題:
* 1.明確哪些代碼是多線程代碼
* 2.明確共享數(shù)據(jù)
* 3.明確多線程代碼中哪些語(yǔ)句是操作共享數(shù)據(jù)的
*/
public class Bank {
private int sum;
Object obj = new Object();
//定義同步函數(shù),在方法錢(qián)用synchronized修飾即可
public synchronized void add(int n) {
//synchronized (obj) {
sumsum = sum + n;
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("sum=" + sum);
//}
}
}
class Cus implements Runnable {
private Bank b = new Bank();
public void run() {
for (int x = 0; x < 3; x++) {
b.add(100);
}
}
}
class BankDemo {
public static void main(String[] args) {
Cus c = new Cus();
Thread t1 = new Thread(c);
Thread t2 = new Thread(c);
t1.start();
t2.start();
}
}
6.同步的鎖
6.1函數(shù)需要被對(duì)象調(diào)用,那么函數(shù)都有一個(gè)所屬對(duì)象引用,就是this.,所以同步函數(shù)使用的鎖是this
6.2.靜態(tài)函數(shù)的鎖是class對(duì)象
靜態(tài)進(jìn)內(nèi)存時(shí),內(nèi)存中沒(méi)有本類(lèi)對(duì)象,但是一定有該類(lèi)對(duì)應(yīng)的字節(jié)碼文件對(duì)象,類(lèi)名.class,該對(duì)象的類(lèi)型是Class
6.3.靜態(tài)的同步方法,使用的鎖是該方法所在類(lèi)的字節(jié)碼文件對(duì)象,類(lèi)名.class
/*
* 需求:簡(jiǎn)買(mǎi)票程序,多個(gè)窗口同時(shí)賣(mài)票
*/
public class Ticket implements Runnable {
private static int tick = 100;
Object obj = new Object();
boolean flag=true;
public void run() {
if(flag){
while (true) {
synchronized (Ticket.class) {
if (tick > 0) {
System.out.println(Thread.currentThread().getName()
+ "code:" + tick--);
}
}
}
}else{
while(true){
show();
}
}
}
public static synchronized void show() {
if (tick > 0) {
System.out.println(Thread.currentThread().getName() + "show:"
+ tick--);
}
}
}
class ThisLockDemo {
public static void main(String[] args) {
Ticket t = new Ticket();
Thread t1 = new Thread(t);
try {
Thread.sleep(10);
} catch (Exception e) {
// TODO: handle exception
}
t.flag=false;
Thread t2 = new Thread(t);
//Thread t3 = new Thread(t);
//Thread t4 = new Thread(t);
t1.start();
t2.start();
//t3.start();
//t4.start();
}
}
【Java多線程的基本使用】相關(guān)文章:
Java多線程基本使用03-30
如何使用java多線程05-04
淺談如何使用java多線程05-07
關(guān)于多線程基本概念的java基本教程參考01-28
java的多線程04-09
java多線程05-11
java多線程教程04-22
java語(yǔ)言的多線程04-19