java线程笔记

1、Thread和Runnable的区别

   Runnable更加面向对象。它把执行者和任务分开独立对象。

2、线程通信

把互斥、相互通信的逻辑任务放在同一个任务中更容易实现。如:

package com.skydream.traditional.thread.communication;

public class Task {

	private boolean flag = true;

	public void print1() throws InterruptedException {
		synchronized (this) {
			while (flag) {
				this.wait();
			}
			for (int i = 0; i < 10; i++) {
				System.out.println("This is the 10 loop " + i);
			}
			flag = true;

			this.notifyAll();
		}
	}

	public void print2() throws InterruptedException {
		synchronized (this) {
			while (!flag) {
				this.wait();
			}
			for (int i = 0; i < 50; i++) {
				System.out.println("50 loops " + i);
			}
			flag = false;

			this.notifyAll();
		}
	}
}


	final Task objTask = new Task();
		new Thread(new Runnable() {
			public void run() {
				try {
					while (true)
						objTask.print2();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}).start();

		while (true) {

			objTask.print1();
		}


3、wait ,notify必须在synchronized代码块中,切他们的所对象相同。

	synchronized (this) {
			while (!flag) {
				this.wait();
			}
			for (int i = 0; i < 50; i++) {
				System.out.println("50 loops " + i);
			}
			flag = false;

			this.notifyAll();
		}

都使用的this。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值