天天看點

Java線程問題總結

public class ThreadTest {
    public static void main(String[] args){
    //    System.out.println("HelloWorld");
        Counter c = new Counter();
       Thread n1 = new Thread(new Run(c));
       n1.setName("n1");
        Thread n2 = new Thread(new Run(c));
        n2.setName("n2");

        n1.start();
        n2.start();
       /* Thread n3 = new Thread(new Run(c));
        n3.setName("n3");
        Thread n4 = new Thread(new Run(c));
        n4.setName("n4");
        Thread n5 = new Thread(new Run(c));
        n5.setName("n5");
*/
        try{
            Thread.currentThread().sleep(1000);
        }catch(InterruptedException e){}


/*
        Thread st = new SonThread("SonThread start");
        st.start();

        System.out.println(Thread.currentThread()); //拿到目前的線程

        try{
            Thread.sleep(1000);
        //    st.join();  //線程合并
        }catch(InterruptedException e){
            e.printStackTrace();
        }



        st.interrupt();
*/


    }
}

class Run implements Runnable{
    String printText;
    Counter c;

    Run(String printText){
       this.printText = printText;
    }

    Run(Counter c){
        this.c = c;
    }

    @Override
    public void run() {
        if(Thread.currentThread().getName().equals("n2")){
            c.test2();
        }else{
            c.test();
        }


    }

}

class SonThread extends Thread{
    String printText;

    SonThread(String printText){
        this.printText = printText;
    }
    @Override
    public void run() {
        yield();

        System.out.println(printText);
        System.out.println(isAlive());
        System.out.println(getPriority());


        try{
            sleep(5000);
            System.out.println("5秒等待完畢!");
        }catch(InterruptedException e){
            e.printStackTrace();
            return;
        }


    }

    @Override
    public synchronized void start() {
        super.start();
        System.out.println("線程啟動後我還要幹一點事情……");
    }
}

class Counter{
    private int num = 0;

    public void add(){
        synchronized(this) {
            num++;
            System.out.println("目前線程名:" + Thread.currentThread().getName() + " num目前值:" + num);

            try {
                Thread.currentThread().sleep(5000);
            } catch (InterruptedException e) {
            }
        }
    }
    public void test(){
        synchronized (this){
            System.out.println("同步調試");

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

    public void test2(){
        synchronized (this) {
            System.out.println("同步調試222");
        }
    }
}

/*
*   synchronized 對象鎖是此對象所擁有的一把鎖,其他同步代碼都會受到這一把鎖的影響
*   線程開啟的兩種方式 一種是實作Runnable接口 另一種則是繼承Thread線程
*   synchronized 隻鎖定被圈定的代碼段 其他未被圈定的代碼不受影響
*   多線程同時調用synchronized線程鎖的代碼,會被放入等待鎖池中
*
* */