java多线程的(hello world)

来源:互联网 发布:淘宝上的组装电脑 编辑:程序博客网 时间:2024/05/16 16:27
public class MyThreadApp implements Runnable {

    // produce
    // consume

    Thread produce = null;

    Thread consume = null;

    public void run() {
        while (true) {
            say();
        }
    }

    /*
     * synchronized 同步
     * 只能有一个线程使用这个方法,别的线程都要等待
     */
    public synchronized void say()
    {
        if (Thread.currentThread() == produce)
            System.out.println("produce");
        else if (Thread.currentThread() == consume)
            System.out.println("consume");
        else
            System.out.println("main");
        try {
            Thread.sleep(600);
            notifyAll();        //唤起所有的线程进行竞争。
        } catch (InterruptedException e) {
        }
       
    }
    public void go() {
        produce = new Thread(this);
        consume = new Thread(this);
        produce.start();
        consume.start();
    }

    public static void main(String[] args) {
        System.out.println("main method started......");
        MyThreadApp myThreadApp = new MyThreadApp();
        myThreadApp.go();
        myThreadApp.run();
        System.out.println("gone!");

    }
}