多線程簡介
多線程是指從軟件或者硬件上實現多個線程併發執行的一種技術。它的使用場景是在CPU出現浪費的時候用的,多線程的出現極大的提高了CPU的利用率。多線程可以實現多個線程同時進行,但是實際上並不是真正的同時進行,在微小的時間段內,還是處理一個線程,只是不斷切換線程。多線程的資源有的是共享資源,既是共享資源就可能會產生幾個線程競爭使用一個資源,這時候就會產生相互干擾的問題了。
簡單多線程代碼
方法進棧中的方法都是拷貝過來的,此時的方法爲棧幀(方法單位)
第一個方法加 . join();上一個方法執行完之後再執行下一個
·start()和run()方法配合使用 兩個線程調用run方法和方法內的變量是拷貝的各自都有對應的run方法
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
Tree tree=new Tree();
tree.value=100;
ThreadDemo t1=new ThreadDemo("2",tree);
t1.start();
ThreadDemo t2=new ThreadDemo("3",tree);
t2.start();
ThreadDemo t3=new ThreadDemo("1",tree);
t3.start();
}
extends Thread 繼承Thread方法 主線程是main方法子線程是thread(另外一個程序)
public class ThreadDemo extends Thread {//extends Thread繼承Thread類
private String name ;
private Tree tree;
ThreadDemo(String name,Tree tree){
this.name=name;
this.tree=tree;
}
public void run() {
StackTest bn=new StackTest();//實例化棧,要配合棧使用,單獨使用會報錯。
while(tree.value>0) {
//try{}catch這個對整個線程起作用
try {
Thread.sleep(10);//休眠10微妙後執行下一個
}catch(InterruptedException e) {
e.printStackTrace();
}
tree.jian();
System.out.println(name+"賣了第"+tree.value+"張");
}
}
}
這裏需要知道一種神祕的“鎖”
這種鎖是java鎖,它是爲了讓線程互不干涉,鎖的是目標資源 ,是由一個版本號和標記組成的。它鎖的是不在方法內部的變量(方法內部的變量是安全的)能鎖住的鎖必須是在同一個區域內的,鎖只能給方法加鎖 不能給資源加鎖。
鎖可以分爲:1對象鎖 2靜態鎖
對象加鎖 :第一個對象鎖 會對第二個非靜態方法進行鎖住
靜態的鎖(static):是相互鎖(第一個方法鎖住第二個方法也能鎖住)
靜態鎖(類鎖)和對象鎖是不能相互鎖的
下面的鎖是鎖不住value的,因爲valueb不是共享資源。
public class ThreadDemo extends Thread{
private String name;
private volatile Tree tree;
ThreadDemo(String name, Tree tree){
this.name = name;
this.tree = tree;
}
public void run() {
ZhanTest bn = new ZhanTest();
for(int i = 0; i < 10000; i++) {
tree.jiajia();
}
}
//這個是鎖不住value的
// public synchronized void run() {
// ZhanTest bn = new ZhanTest();
// for(int i = 0; i < 10000; i++) {
// tree.value++;
// }
//
// }
}
總結:
Java中線程的共享互斥操作,會使用synchronized(鎖)關鍵字解決多線程中出現的問題。