線程的創(chuàng)建方式
糾正一下線程的創(chuàng)建方式绍刮,之前很多博客都寫有三種方式温圆,翻看了一下Thread的源碼發(fā)現(xiàn)只有兩種方式。
1.繼承Thread
2.實現(xiàn)Runnable
* There are two ways to create a new thread of execution. One is to
* declare a class to be a subclass of <code>Thread</code>. This
* subclass should override the <code>run</code> method of class
* <code>Thread</code>. An instance of the subclass can then be
* allocated and started. For example, a thread that computes primes
* larger than a stated value could be written as follows:
* <hr><blockquote><pre>
* class PrimeThread extends Thread {
* long minPrime;
* PrimeThread(long minPrime) {
* this.minPrime = minPrime;
* }
*
* public void run() {
* // compute primes larger than minPrime
* . . .
* }
* }
* </pre></blockquote><hr>
* <p>
* The following code would then create a thread and start it running:
* <blockquote><pre>
* PrimeThread p = new PrimeThread(143);
* p.start();
* </pre></blockquote>
* <p>
* The other way to create a thread is to declare a class that
* implements the <code>Runnable</code> interface. That class then
* implements the <code>run</code> method. An instance of the class can
* then be allocated, passed as an argument when creating
* <code>Thread</code>, and started. The same example in this other
* style looks like the following:
* <hr><blockquote><pre>
* class PrimeRun implements Runnable {
* long minPrime;
* PrimeRun(long minPrime) {
* this.minPrime = minPrime;
* }
*
* public void run() {
* // compute primes larger than minPrime
* . . .
* }
* }
* </pre></blockquote><hr>
* <p>
* The following code would then create a thread and start it running:
* <blockquote><pre>
* PrimeRun p = new PrimeRun(143);
* new Thread(p).start();
* </pre></blockquote>
* <p>
至于為什么實現(xiàn)Callable不能算作一種方式录淡,是因為Callable我們需要交給FutureTask來處理捌木,而FutureTask又是Runnable的子類。
線程的狀態(tài)
回顧一下線程的狀態(tài)
1.可運行狀態(tài)
2.運行狀態(tài)
3.阻塞狀態(tài) 使用synchronized加鎖
4.等待狀態(tài) 使用wait嫉戚,sleep刨裆,join以及顯示鎖
5.死亡狀態(tài)
死鎖
死鎖就是有兩個線程或者兩個以上線程,A線程獲取了A資源之后還想獲取B資源彬檀,B線程獲取了B資源之后還想獲取A資源帆啃,彼此都不放棄自己持有的資源。
public class Lock {
static ReentrantLock lock=new ReentrantLock();
static ReentrantLock lock1=new ReentrantLock();
static class ThreadA extends Thread{
@Override
public void run() {
super.run();
synchronized (lock){
System.out.println("lock");
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lock1){
System.out.println("lock1");
}
}
}
}
static class ThreadB extends Thread{
@Override
public void run() {
super.run();
synchronized (lock1){
System.out.println("lock1");
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lock){
System.out.println("lock");
}
}
}
}
public static void main(String[] args){
new ThreadA().start();
new ThreadB().start();
}
}
死鎖的條件:
1.互斥條件
2.保持持有資源
3.不剝奪已有資源
4.環(huán)路等待
解決死鎖
1.設(shè)定請求鎖的順序
public class Lock {
static ReentrantLock lock=new ReentrantLock();
static ReentrantLock lock1=new ReentrantLock();
static class ThreadA extends Thread{
@Override
public void run() {
super.run();
synchronized (lock){
System.out.println("lock");
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lock1){
System.out.println("lock1");
}
}
}
}
static class ThreadB extends Thread{
@Override
public void run() {
super.run();
synchronized (lock){
System.out.println("lock");
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lock1){
System.out.println("lock1");
}
}
}
}
public static void main(String[] args){
new ThreadA().start();
new ThreadB().start();
}
}
2.使用tryLock嘗試請求鎖
public class Lock {
static ReentrantLock lock = new ReentrantLock();
static ReentrantLock lock1 = new ReentrantLock();
static class ThreadA extends Thread {
@Override
public void run() {
super.run();
while (true) {
if (lock.tryLock()) {
System.out.println(Thread.currentThread().getName() + "lock");
try {
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (lock1.tryLock()) {
try {
System.out.println(Thread.currentThread().getName() + "lock1");
break;
} finally {
lock1.unlock();
}
}
} finally {
lock.unlock();
}
}
}
}
}
static class ThreadB extends Thread {
@Override
public void run() {
super.run();
while (true) {
if (lock1.tryLock()) {
System.out.println(Thread.currentThread().getName() + "lock1");
try {
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (lock.tryLock()) {
try {
System.out.println(Thread.currentThread().getName() + "lock");
break;
} finally {
lock.unlock();
}
}
} finally {
lock1.unlock();
}
}
}
}
}
public static void main(String[] args) {
new ThreadA().start();
new ThreadB().start();
}
}
發(fā)現(xiàn)無法獲取內(nèi)部的鎖窍帝,造成了活鎖努潘,線程還在一直運行但是無法執(zhí)行內(nèi)部的代碼,一直在獲取鎖坤学,釋放鎖疯坤。
解決方法:
在釋放掉鎖之后等待一段不同的時間
public class Lock {
static ReentrantLock lock = new ReentrantLock();
static ReentrantLock lock1 = new ReentrantLock();
static class ThreadA extends Thread {
@Override
public void run() {
super.run();
while (true) {
if (lock.tryLock()) {
System.out.println(Thread.currentThread().getName() + "lock");
try {
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (lock1.tryLock()) {
try {
System.out.println(Thread.currentThread().getName() + "lock1");
break;
} finally {
lock1.unlock();
}
}
} finally {
lock.unlock();
}
}
try {
sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
static class ThreadB extends Thread {
@Override
public void run() {
super.run();
while (true) {
if (lock1.tryLock()) {
System.out.println(Thread.currentThread().getName() + "lock1");
try {
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (lock.tryLock()) {
try {
System.out.println(Thread.currentThread().getName() + "lock");
break;
} finally {
lock.unlock();
}
}
} finally {
lock1.unlock();
}
}
try {
sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
new ThreadA().start();
new ThreadB().start();
}
}
ThreadLocal
在Handler中使用了ThreadLocal用來保存Looper,使得每個線程有自己的Looper深浮⊙沟。可以起到數(shù)據(jù)隔離的作用。
內(nèi)部原理:
由于每個Thread都有一個ThreadLocal.ThreadLocalMap的成員變量飞苇,ThreadLocalMap中存放了一個Entry[]菌瘫,key就是ThreadLocal,value就是存放的值布卡。數(shù)組是因為一個線程可以有多個ThreadLocal雨让。
當ThreadLocal.set的時候,首先獲取了當前線程的ThreadLocalMap忿等。
樂觀鎖(CAS) compare and swap
通常我們使用的類鎖栖忠,對象鎖,顯示鎖都是悲觀鎖这弧,當某一個線程拿到鎖之后其他線程就無法拿到鎖娃闲。
樂觀鎖可以保證原子操作,在對變量進行操作的時候匾浪,多個線程可以同時進入代碼執(zhí)行皇帮,但是會攜帶一個初始的值,進入CAS的時候會拿著初始值和此線程攜帶的初始值進行比較蛋辈,如果一致那么就可以將此線程的值進行更新属拾。如果不一致那么就重新執(zhí)行代碼進行計算将谊,然后再比較....此處是一個死循環(huán)
樂觀鎖的問題
1.ABA
變量原始為A,線程1將變量修改為B渐白,而線程2將變量修改成C尊浓,然后又修改成A,這個時候就出現(xiàn)問題了纯衍。
解決方法:加入版本戳栋齿,可以理解為一個計數(shù)器,如果初始值相同襟诸,并且計數(shù)器為0瓦堵,那么就是沒有被別人修改過
例如:AtomicMarkableReference(有版本戳),AtomicStampedReference(有版本戳并且可以獲取被修改了幾次)
2.資源開支 線程競爭比較激烈的時候,死循環(huán)
3.只能對一個變量進行原子操作 AtomicReference(將修改的變量封裝成一個類歌亲,就可以對多個變量進行原子操作了)