002JAVA多個多線程同時競爭一個類實例方法

package com.skcc.mthread;

public class MyThread001 extends Thread {

private int count=4;

public MyThread001() {
    // TODO Auto-generated constructor stub
}

@Override
public synchronized void run() {
   count--;
   System.out.println(Thread.currentThread().getName() + " = " + count);
}

/***
 * 多個線程同時競爭MyThread001類實例對象及成員方法
 * 多個線程按照CPU分配時間順序來執行,(t1到t4的執行順序需參考CPU分配的順序來定)
 * 
 * ****/
public static void main(String[] args) {
    // TODO Auto-generated method stub
    MyThread001 myThread = new MyThread001();

    Thread t1 = new Thread(myThread,"t1");
    Thread t2 = new Thread(myThread,"t2");
    Thread t3 = new Thread(myThread,"t3");
    Thread t4 = new Thread(myThread,"t4");

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

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章