`
xiang37
  • 浏览: 417392 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

多线程简单示例

 
阅读更多

多线程的一个简单示例

 

主要使用notify与wait方法。

 

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.xiva.baseKnowledge;

import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Administrator
 */

public class MutiThread {

    public static int count = 0;
    //public static boolean mutex = true;

    public synchronized void print() {    
        System.out.println(count);
    }

    public synchronized void add(int i) {
        count = count + i;
        System.out.println("add");
    }

    public static void main(String[] args) {
        MutiThread mThread = new MutiThread();
        PrintThread pThread = new PrintThread(mThread);
        AddThread addThread = new AddThread(pThread);
        addThread.start();
        pThread.start();
    }
}

class  PrintThread extends Thread {

    private final MutiThread mThread;
    
    private volatile boolean startP = false;
    
    public PrintThread(MutiThread mThread) {
        this.mThread = mThread;
    }
    
    public MutiThread getMThread(){
        return this.mThread;
    }
    
    public synchronized void notifyPrint(){
      startP = true;
      notify();
    }
    
    public synchronized void print(){
        if(startP){
            try {
                TimeUnit.SECONDS.sleep(2);
                mThread.print();
                startP = false;
            } catch (InterruptedException ex) {
                Logger.getLogger(PrintThread.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        else{
            try {
                wait();
            } catch (InterruptedException ex) {
                Logger.getLogger(AddThread.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    
    
    @Override
    public void run() {
        while (true) {
            print();
        }
    }
}

class AddThread extends Thread {

    private final PrintThread pThread;
    
    public AddThread(PrintThread pThread) {
        this.pThread = pThread;
    }
        
    @Override
    public void run() {
        for (int i = 1; i < 1000; i++) {
            try {
                //Thread.sleep(5000);
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException ex) {
                Logger.getLogger(MutiThread.class.getName()).log(Level.SEVERE, null, ex);
            }
            pThread.getMThread().add(i);
            pThread.notifyPrint();
        }
    }
}
 其中的锁机制有待改进。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics