1. 程式人生 > >多執行緒第三旅

多執行緒第三旅

3..多執行緒常用操作方法

3.1執行緒命名與取得

a.通過構造方法在建立執行緒時設定執行緒名

public Thread (string name)

public Thread(Runnable target,String name)

b.取得執行緒名稱

public final  String getname()

c.設定執行緒名稱

public   final  synchronized void setName(String name)

見程式碼:package www.wl.java;
class MyThread implements Runnable {
    @Override


    public void run() {
        for (int i = 0; i < 10 ; i++) {
            System.out.println("當前執行緒:" + Thread.currentThread().getName() + " ,i =  " + i);
        }
    }
}

public class Test{
    public static void main(String[] args) {
        MyThread mt = new MyThread() ;
        new Thread(mt).start();
// 沒有設定名字
new Thread(mt).start(); // 三個執行緒分別呼叫三次Run()
new Thread(mt,"yuisamaa").start(); // 有設定名字
}
}

證明主方法是個執行緒:

package www.wl.java;
class MyThread implements Runnable {
    @Override
    public void run() {

            System.out.println( Thread.currentThread().getName() );

    }
}

public class Test {
    public static void

main(String[] args) {
        Thread thread = new Thread(new MyThread());
        thread.run();
    }
}

3.2執行緒睡眠(sleep)方法--單位為毫秒,立即交出CPU,返回阻塞態

Public static native void sleep(long millis)throws InterruptedException

執行緒休眠:讓當前執行緒暫緩執行等到了預計時間後再恢復執行

執行緒休眠會交出CPU,但不會釋放鎖

程式碼:

package www.bit.java;
class MyThread implements Runnable {
    @Override
    public void run() {
for (int i = 0;i<3;i++) {
    System.out.println(Thread.currentThread().getName()+","+i);
    try {
        Thread.sleep(2000);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
    }
}
public class Test {
    public static void main(String[] args) {
        MyThread mt=new MyThread();
        Thread thread1 = new Thread(mt,"A");
        Thread thread2 = new Thread(mt,"B");
        Thread thread3 = new Thread(mt,"C");
        thread1.start();
        thread2.start();
        thread3.start();
    }
}

結果:肯定會有交替,因為sleep是立即交出CPU

C,0

A,0

B,0

C,1

A,1

B,1

A,2

B,2

C,2

3.3執行緒讓步(yield)方法,不確定交CPU時間,返回就緒態

暫停執行當前的執行緒物件,並執行其他執行緒

(yield)方法會讓當前執行緒交出CPU,同樣不會釋放鎖,但是(yield)方法無法控制具有交出cpu的時間,並且(yield)方法只能讓擁相同優先順序的執行緒有機會獲取CPU的機會

package www.bit.java;
class MyThread implements Runnable {
    @Override
    public void run() {
for (int i = 0;i<3;i++) {
    System.out.println(Thread.currentThread().getName() + "," + i);
    Thread.yield();
}
    }
}
public class Test {
    public static void main(String[] args) {
        MyThread mt=new MyThread();
        Thread thread1 = new Thread(mt,"A");
        Thread thread2 = new Thread(mt,"B");
        Thread thread3 = new Thread(mt,"C");
        thread1.start();
        thread2.start();
        thread3.start();
    }
}

結果:不確定CPU交出的時間,可能執行完自己的執行緒後才會交出CPU

A,0

A,1

B,0

C,0

A,2

B,1

C,1

B,2

C,2

複習

1.JAVA中多執行緒實現方法

1.1繼承Thread類,覆寫run方法(輔助執行緒啟動)

1.2實現Runnable介面,覆寫run方法

1.3實現Callable<v>介面,覆寫call<v>方法

  1. 操作方法

2.1執行緒名稱

2.2執行緒休眠(sleep)(從執行到阻塞狀態),不會釋放鎖,立即交出cpu

休眠時間結束後,從阻塞態到就緒態

2.3執行緒讓步(yield)執行態到就緒態,不會釋放鎖

不一定立即交出CPU,從就緒態到執行態