多線程實現有倆種方法(僅限於我這個初學多線程的娃):
①繼承自Thread類的類對象;
②實現於Runnable接口的類對象。
二者的區別是:Thread: 一個Mythread(繼承他的類對象)代表一個線程,故Mythread裏面的資源不可共享;
Runnable: Thread修飾MyRunnable,一個Thread代表一個線程,故同一個MyRunnable裏面的資源可共享。
public class RunnableandThreadDemo {
public static void main(String[] args) {
System.out.println(" 我們先使用繼承Tread類的三個MyThread對象線程運行。\n\n");
saleticketsTread();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("\n 現在主線程休眠二秒... ...\n");
System.out.println("\n現在採用實現Runnable接口的MyRunnable(Thread修飾)的三個接口(共享一個MyRunnable對象,從而實現了資源共享)....\n");
saleticketsRunnable();
}
public static void saleticketsTread() {
Mythread my1 = new Mythread("1號Tread類型窗口");
Mythread my2 = new Mythread("2號Tread類型窗口");
Mythread my3 = new Mythread("3號Tread類型窗口");
my1.start();
my2.start();
my3.start();
}
public static void saleticketsRunnable() {
MyRunnable my = new MyRunnable(); // 實例化MyRunnale(Runnale接口)再用Thread裝飾
MyRunnable my2 = new MyRunnable();
Thread thr1 = new Thread(my, "Thread裝飾的Runnale壹號窗口");
Thread thr2 = new Thread(my, "Thread裝飾的Runnale二號窗口");
Thread thr3 = new Thread(my, "Thread裝飾的Runnale三號窗口");
thr1.start();
thr2.start();
thr3.start();
}
}
/**一個Mythread代表一個線程,故Mythread裏面的資源不可共享**/
class Mythread extends Thread { // Mythread繼承Thread類,覆寫Run方法,不共享資源
private int tickets = 3;
private String windowname; // 需要自己寫賦予線程名字
public Mythread(String windowname) {
super();
this.windowname = windowname;
}
public void run() {
for (int i = 0; i < 4; i++) {
if (tickets > 0) {
System.out.println(windowname + "正在賣第" + tickets-- + "張票");
}
}
}
}
/**Thread修飾MyRunnable,一個Thread代表一個線程,故同一個MyRunnable裏面的資源可共享**/
class MyRunnable implements Runnable {
private int tickets = 3;
@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i < 4; i++) {
if (tickets > 0) {
System.out.println(Thread.currentThread().getName() + "正在賣第" + tickets-- + "張票");
}
}
}
}
下附線程常用的方法: Thread.currentThead() ->當前線程可加上 ".getname()"等方法。 (th爲Thread的對象) th.isAlive() ——>判斷線程是否死亡。 Thread.sleep(ms)。 th.join()強制運行 th.ionterrupt()強制中斷 th.stePriority(x) x= (1,10)設置優先值 。。。可能不盡如人意。。。 th.yied() 暫時禮讓,稍後恢復。