Java線程通信源代碼中的奧秘探究
作者:佚名
Java線程通信不斷的使用中會有很多問題出現,有不少的人不知道如何去解決。其實我們就來看看Java線程通信的源代碼。
Java線程通信在使用的時候需要我們不斷學習,在學習的時候會有很多的問題存在。其實我們在源代碼中就能發現其中的奧秘。因為ThreadNum和ThreadChar都有對Objecto的引用,所以你wait和notify的時候都應該同步,Java線程通信具體看如下:
- public class Test8 {
- public static void main(String[] args){
- Object o=new Object();
- Thread n=new ThreadNum(o);
- Thread c=new ThreadChar(o);
- n.start();
- c.start();
- }
- }
- class ThreadNum extends Thread{
- Object o;
- public ThreadNum(Object o){
- this.o=o;
- }
- public void run(){
- for(int i=1;i<26;i++){
- System.out.println(i);
- System.out.println(++i);
- try {
- synchronized (this) {
- this.wait();
- }
- } catch (InterruptedException e) {}
- synchronized (this) {
- this.notify();
- }
- }
- }
- }
- class ThreadChar extends Thread{
- Object o;
- public ThreadChar(Object o){
- this.o=o;
- }
- public void run(){
- for(char a='A';a<='Z';a++){
- System.out.println(a);
- synchronized (this) {
- this.notify();
- }
- try {
- synchronized (this) {
- this.wait();
- }
- } catch (InterruptedException e) {}
- }
- }
- }
以上就是對Java線程通信的詳細介紹。
【編輯推薦】
責任編輯:張浩
來源:
互聯網