主程式代碼:
public class MainApp {
public static void main(String[] args) {
try {
MySprite dog = new MySprite("狗狗");
MySprite cat = new MySprite("喵喵");
MySprite pig = new MySprite("豬豬");
System.out.println("--- start sprites");
dog.start();
cat.start();
pig.start();
Thread.sleep(500);
System.out.println("--- suspend dog");
dog.suspend();
System.out.println("--- main thread do something");
Thread.sleep(500);
System.out.println("--- resume dog");
dog.resume();
Thread.sleep(500);
System.out.println("--- end dog");
dog.stop();
System.out.println("--- main thread do something");
Thread.sleep(500);
System.out.println("--- end other sprites");
cat.stop();
pig.stop();
Thread.sleep(100);
System.out.println("--- exit programe.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
線(xiàn)程實(shí)現
public class MySprite implements Runnable {
/**//*
* 線(xiàn)程用變量
*/
private boolean running = false;
private boolean waiting = false;
private Thread thread;
/**//*
* Business 變量
*/
private String name;
public MySprite(String name) {
this.name = name;
this.thread = new Thread(this);
}
/** *//**
* 啟動(dòng)線(xiàn)程
*/
public void start() {
running = true;
thread.start();
}
/** *//**
* 掛起線(xiàn)程
*/
public void suspend() {
if (waiting) { // 是掛起狀態(tài)則直接返回
return;
}
synchronized (this) {
this.waiting = true;
}
}
/** *//**
* 恢復線(xiàn)程
*/
public void resume() {
if (!waiting) { // 沒(méi)有掛起則直接返回
return;
}
synchronized (this) {
this.waiting = false;
this.notifyAll();
}
}
/** *//**
* 停止線(xiàn)程
*/
public void stop() {
if (!running) { // 沒(méi)有運行則直接返回
return;
}
synchronized (this) {
running = false;
}
}
public void run() {
for(;;) {
try {
// 線(xiàn)程掛起和退出處理
synchronized (this) {
if (!running) {
break;
}
if (waiting) {
this.wait();
}
}
// 應該做的事情
cry();
// 進(jìn)入等待狀態(tài)
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void cry() {
System.out.println(name + ":woo!");
}
}
可以結合UDP,TCP進(jìn)行網(wǎng)絡(luò )編程使用。在使用UDP時(shí),由于DatagramSocket在接收數據的時(shí)候需要等待,程序不能進(jìn)行停止的操作,所以要給datagramSocket加一個(gè)定時(shí)器,超時(shí)則進(jìn)行下一次接收的過(guò)程。我在jbuilder中已經(jīng)做好了一個(gè),以后放上來(lái)做詳細介紹。
本站僅提供存儲服務(wù),所有內容均由用戶(hù)發(fā)布,如發(fā)現有害或侵權內容,請
點(diǎn)擊舉報。