新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
Java線程通信源代碼中的奧秘探究
Java線程通信在使用的時候需要我們不斷學(xué)習(xí),在學(xué)習(xí)的時候會有很多的問題存在。其實(shí)我們在源代碼中就能發(fā)現(xiàn)其中的奧秘。因為ThreadNum和ThreadChar都有對Objecto的引用,所以你wait和notify的時候都應(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) {}
- }
- }
- }
以上就是對Java線程通信的詳細(xì)介紹。
文章標(biāo)題:Java線程通信源代碼中的奧秘探究
URL網(wǎng)址:http://m.fisionsoft.com.cn/article/cohdigh.html


咨詢
建站咨詢
