先來個小總結:
yield()使當前線程暫停。但設置了setPriority(Thread.MAX_PRIORITY);時,yield()不咋管用了。
一般只需要重寫run()方法的話,實現runnalbe接口比較方便。
如果在進程類里面需要訪問同一個變量的話,就實現接口。如果用繼承類的話,同一個變量就有幾份的拷貝。但是內部類繼承類的結和繼承接口的效果一樣。
啟動一個線程
MyThread mt=new MyThread();
new Thread(mt).start();
好多東西都有時間片。時間片是個不確定的東西。
當調用wait(),notify()方法時,應該保證他們是同一個對象sy也要同一個對象。synchronized 中 才能有wait(),notify()方法。
synchronized(Object obj)與synchronized(this)的區別?!(誰能告訴我!!!!!)
下面是生產者與消費者的例子,為了方便,幾個類直接寫在一起了。
//new 生產者,消費者,隊列。并起用生產者,消費者的線程
public class Test {
?public static void main(String[] args) {
??Queue q = new Queue();
??Producer p = new Producer(q);
??Consumer c = new Consumer(q);
??p.start();
??c.start();
?}
}
//生產者,每生產好一個東西后,就往隊列中放一個
class Producer extends Thread {
?Queue q;
?Producer(Queue q) {
??this.q = q;
?}
?public void run() {
??for (int i = 0; i < 10; i++) {
???q.setValue(i);
???System.out.println("Producer put:" + i);
??}
?}
}
//消費者,每當隊列中有東西通知時,就從隊列去拿
class Consumer extends Thread {
?Queue q;
?Consumer(Queue q) {
??this.q = q;
?}
?public void run() {
??while (true) {
???System.out.println("Consumer get:" + q.getValue());
??}
?}
}
//隊列
class Queue {
?int value;
?boolean flag = false;
?//生產者往這放它所生產的東西
?public synchronized void setValue(int i) {
??//當生產好一個往隊列中放了后,放置一個標志。發個通知,告訴說生產好了,并等待消費者來拿
??if (!flag) {
???value = i;
???flag = true;
???notify();
??}
??try {
???wait();
??} catch (InterruptedException e) {
???e.printStackTrace();
??}
?}
?//消費者從這獲取東西
?public synchronized int getValue() {
??//消費這先判斷隊列是否有東西了,有的話,就讓其他線程等待,自己取拿,拿好后設置一個標志,發個通告告訴其他線程,我拿好了
??if (!flag) {
???try {
????wait();
???} catch (InterruptedException e) {
????e.printStackTrace();
???}
??}
??flag = false;
??notify();
??return value;
?}
}
posted on 2007-01-15 00:27
xrzp 閱讀(845)
評論(0) 編輯 收藏 所屬分類:
JAVA