Java線程通信源代碼中的奧秘探究
作者:佚名
Java線程通信不斷的使用中會(huì)有很多問(wèn)題出現(xiàn),有不少的人不知道如何去解決。其實(shí)我們就來(lái)看看Java線程通信的源代碼。
Java線程通信在使用的時(shí)候需要我們不斷學(xué)習(xí),在學(xué)習(xí)的時(shí)候會(huì)有很多的問(wèn)題存在。其實(shí)我們?cè)谠创a中就能發(fā)現(xiàn)其中的奧秘。因?yàn)門hreadNum和ThreadChar都有對(duì)Objecto的引用,所以你wait和notify的時(shí)候都應(yīng)該同步,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) {}
- }
- }
- }
以上就是對(duì)Java線程通信的詳細(xì)介紹。
【編輯推薦】
責(zé)任編輯:張浩
來(lái)源:
互聯(lián)網(wǎng)