?? mthreaddemo.java
字號:
class MThreadDemo
{
static public void main(String[] args)
{
//創建一個新的線程組group01,名稱為ThreadGroup01
ThreadGroup group01 = new ThreadGroup("ThreadGroup01");
group01.setMaxPriority(4);
//創建新線程,并加入到線程組group01中
Thread query01 = new Thread(group01,new Query(),"Query01");
Thread query02 = new Thread(group01,new Query(),"Query02");
Thread query03 = new Thread(group01,new Query(),"Query03");
//創建一個新的線程組group02,名稱為ThreadGroup02
ThreadGroup group02 = new ThreadGroup("ThreadGroup02");
//創建新線程,并加入到線程組group02中
Thread transaction01 = new Thread(group02,new Transaction(),"Transaction01");
Thread transaction02 = new Thread(group02,new Transaction(),"Transaction02");
//向屏幕輸出當前所有線程組的信息
System.out.println("============================================" );
System.out.println("線程組group01中的線程有:" );
group01.list(); //顯示線程組group01中的所有線程
System.out.println("線程組group02中的線程有:" );
group02.list(); //顯示線程組group01中的所有線程
System.out.println("============================================" );
query01.start(); //啟動線程
query02.start();
query03.start();
transaction01.start();
transaction02.start();
}
}
class Query implements Runnable
{
public void run() //在此處放置處理實際任務的代碼
{
//讓線程總共睡眠3次
for(int cnt = 1; cnt < 6; cnt++)
{
try{
//睡眠一個隨機的毫秒數
Thread.currentThread().sleep(
(int)(Math.random() * 100));
}catch(InterruptedException e){}
//顯示當前線程的信息
System.out.println(Thread.currentThread() +
"運行,次數是:" + cnt);
}
}
}
class Transaction implements Runnable
{
public void run() //在此處放置處理實際任務的代碼
{
//讓線程總共睡眠3次
for(int cnt = 1; cnt < 6; cnt++)
{
try{
if(cnt>2)
//睡眠一個隨機的毫秒數
Thread.currentThread().sleep(
(int)(Math.random() * 100));
}catch(InterruptedException e){}
//顯示特定當前的信息
System.out.println(Thread.currentThread() +
"運行,次數是:" + cnt);
}
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -