天天看點

java 多線程

一個java應用程式至少有2個線程: 一個是主線程負責main方法代碼的執行。一個是垃圾回收器線程,負責了回收垃圾。

多線程的好處:1.解決了一個程序能同時執行多個任務的問題。  2. 提高了資源使用率。

多線程的弊端: 1. 增加了cpu的負擔  2. 降低了一個程序中線程的執行效率  3. 引發了線程安全問題。  4. 出現了死鎖現象

java 多線程
sleep()還是會擁有鎖, wati()執行後,就不再擁有鎖 
java 多線程

Sleep()

import java.util.Date;

public class TestInterrupt {
    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start();

        try{
            Thread.sleep(10000);
        }catch(InterruptedException e) { }

        thread.interrupt();// 打斷線程,線程會抛出異常
    }
}


class MyThread extends Thread{

    @Override
    public void run(){
        while(true){
            System.out.println("====="+new Date()+"====");
            try{
                sleep(1000);
            }catch(InterruptedException e) {
                return;
            }
        }
    }
}           

join()

public class TestJoin {
    public static void main(String[] args) {

        MyThread2 t1 = new MyThread2("t1");
        t1.start();

        try{
            t1.join();  // 合并t1 把另外一個線程合并到目前線程一起執行. 相當于方法調用
        }catch(InterruptedException e) { }

        for(int i=0; i<10;i++){
            System.out.println("i am main thread");
        }
    }
}

class MyThread2 extends Thread{
    MyThread2(String s){
        super(s);
    }

    @Override
    public void run() {
        for(int i=0; i<10;i++){
            System.out.println("i am "+getName());
            try{
                sleep(1000);
            }catch(InterruptedException e) {
                return;
            }
        }
    }
}
           

yield()

public class TestYield {

    public static void main(String[] args) {
        MyThread3 t1 = new MyThread3("t1");
        MyThread3 t2 = new MyThread3("t2");

        t1.start();
        t2.start();
    }
}

class MyThread3 extends Thread{
    MyThread3(String s){
        super(s);
    }

    @Override
    public void run(){
        for(int i=1; i<100; i++){
            System.out.println(getName()+"  "+i);
            if(i%10 == 0){
                yield(); // 讓出cpu,給其他線程執行的機會
            }
        }
    }
}
           

設定線程優先級

public class TestPriority {
    public static void main(String[] args) {

        // 線程的優先級用數字表示,範圍從1到10,一個線程的預設優先級是5
        Thread t1 = new Thread(new T1());
        Thread t2 = new Thread(new T2());
        t1.setPriority(Thread.NORM_PRIORITY+3);



        t1.start();
        t2.start();

    }
}


class T1 implements Runnable{

    @Override
    public void run() {
        for(int i=0; i<1000; i++){
            System.out.println("T1: "+i);
        }
    }
}

class T2 implements Runnable{

    @Override
    public void run() {
        for(int i=0; i<1000; i++){
            System.out.println("------T2: "+i);
        }
    }
}           

synchronized

public class Test implements Runnable{

    Timer timer = new Timer();

    public static void main(String[] args) {
        Test test = new Test();
        Thread t1 = new Thread(test);
        Thread t2 = new Thread(test);

        t1.setName("t1");
        t2.setName("t2");
        t1.start();
        t2.start();
    }

    @Override
    public void run() {
        timer.add(Thread.currentThread().getName());
    }
}

class Timer{
    private static int num = 0;
    public synchronized  void add(String name){ // 執行這個方法過程中,目前對象被鎖定
        //synchronized (this) { // 鎖定目前對象, 一個線程進入鎖定區域中,不可能有另一個線程還在這裡邊
            num++;
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
            }

            System.out.println(name + ", 你是第" + num + "個使用timer的線程");
       // }
    }
}
           

synchronized死鎖

public class TestDeadLock implements Runnable{

    public int flag = 1;
    static Object o1 = new Object(), o2 = new Object();

    @Override
    public void run() {
        System.out.println("flag="+flag);
        if(flag == 1){
            synchronized (o1) {
                try {
                    Thread.sleep(500);
                } catch (Exception e) {
                    e.printStackTrace();
                }


                synchronized (o2) {
                    System.out.println("1");
                }
            }
        }

        if(flag == 0){
            synchronized (o2) {
                try {
                    Thread.sleep(500);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                synchronized (o1) {
                    System.out.println("0");
                }
            }
        }
    }

    public static void main(String[] args) {
        TestDeadLock td1 = new TestDeadLock();
        TestDeadLock td2 = new TestDeadLock();
        td1.flag = 1;
        td2.flag = 0;
        Thread t1 = new Thread(td1);
        Thread t2 = new Thread(td2);
        t1.start();
        t2.start();
    }
}
           

生産者,消費者

public class ProducerConsumer {
    public static void main(String[] args) {
        SyncStack ss = new SyncStack();
        Producer producer = new Producer(ss);
        Consumer consumer = new Consumer(ss);
        //System.out.println(Thread.currentThread().getName());
        new Thread(producer,"abc").start();
        new Thread(consumer).start();
    }
}

class Producer implements Runnable{
    SyncStack ss = null;

    public Producer(SyncStack ss){
        this.ss = ss;
    }

    @Override
    public void run(){
        for(int i=1; i<=20; i++){
            Woto w = new Woto(i);
            ss.push(w);
            try {
                Thread.sleep(10);
                // System.out.println("Thread Name: "+Thread.currentThread().getName());
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
    }
}

class Consumer implements Runnable{
    SyncStack ss = null;

    public Consumer(SyncStack ss){
        this.ss = ss;
    }

    @Override
    public void run(){
        for(int i=1; i<=20; i++){
            Woto w = ss.pop();
            try {
                Thread.sleep(1000);
                // System.out.println("Thread Name: "+Thread.currentThread().getName());
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
    }
}


class SyncStack{
    Woto[] wotos = new Woto[6];
    int index = 0;

    public synchronized void push(Woto woto){
        while(index == wotos.length){
            try {
                this.wait();// 線程進入阻塞
                //this.notify();
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
        this.notify(); // 喚醒其他線程
        System.out.println("生成了"+woto);
        wotos[index++] = woto;
    }

    public synchronized Woto pop(){
        while(index == 0){
            try {
                this.notify();
                this.wait();

            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }

        this.notify();
        Woto w = wotos[--index];
        System.out.println("消費"+w);
        return w;
    }
}

class Woto{
    int id;
    public Woto(int id){
        this.id = id;
    }

    public String toString(){
        return "Woto: "+id;
    }
}