多线程 -- 初学简单例子

多线程初学

  • 该模式是生产者--消费者模式。
  • 规定了两个任务内部类,Consumer 和Producer .
  • Producer负责给 num 加1,Consumer 负责给num 减 1。
  • run()方法只是负责任务,不负责启动。
  • 通过 new Thread(new Producer()) 将任务分配给线程。通过start()方法开启线程。
  • Main 线程中有 线程Consumer 的实例consumer ,以及Producer 的实例 producer,所以可以说看的到另外两个线程,所以可以对其他线程进行一定程度的操作。
  • consumer ,producer不知道Main线程,彼此也不知道,所以可以通过Main线程作为中介,使之发生联系。比如说,在main中,将producer传给consumer(一般不建议这么做。),可以使用监听者模式
  • synchronized注意同步,为了正确共享资源。


代码如下:

package tree.test.testThread;

import java.util.Observable;
import java.util.Observer;

public class TestConsumer {

	public static int num = 0;
	public final static int CONSUMER_SLEEP_TIME = 50;
	public final static int PRODUCER_SLEEP_TIME = 40;

	@SuppressWarnings("deprecation")
	public static void main(String[] args) {

		System.out.println("started `````");
		Thread consumer = new Thread(new Consumer());
		Thread producer = new Thread(new Producer());
		consumer.start();
		producer.start();
		try {
			Thread.sleep(2000);
			Thread.yield();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("ended `````");
		//TODO main thread tell others to stop 
		consumer.stop();
		producer.stop();

	}

	static class Producer implements Runnable,Observer {

		public void run() {
			synchronized (this) {
				while (true) {

					num++;
					System.out.println("after produce , num = " + num);
					try {
						Thread.sleep(PRODUCER_SLEEP_TIME);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}

		}

		public void update(Observable o, Object arg) {
			//TODO how to use the pattern observer to control the thread end time .
		}

	}

	static class Consumer implements Runnable {

		public void run() {
			synchronized (this) {
				while (true) {
					try {

						if (num > 0) {
							num--;
							System.out.println("after consume , num = " + num);
						} else {
							System.out.println("nothing in the pool !!");
						}
						Thread.sleep(CONSUMER_SLEEP_TIME);

					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}

		}

	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值