Java基础50线程回顾

Test1:

public class Test1 {
	public static void main(String[] args) {
		Thread thread = new Thread() {
			public void run() {//是否必须重写run方法?不是,但是要实现自己需要的功能就必须重写run方法。
				pong();
			}

		};
		thread.start();
		System.out.println("ping");
	}

	static void pong() {
		System.out.println("pong");
	}
}
	lock和synchronized 对比
	1、特色:reentainLock 可以维持公平性、响应中断、超时机制

	2、性能:并发不严重sync更优,高并发reentainLock好。

	3、底层实现:sync和lock 有同步队列、也有等待队列,sync是基于 object 的wait/notify,lock 是基于condition的await/sigal,底层是locksupport.park/unpark。

	4synchronized 和 lock 在高并发下 ,lock 更优秀。 原因在哪里?

	       1)行为划分

	       2)代码实现细节上的调优

	       3)非阻塞 

	       4) 资源粒度的划分

callable实现多线程:

import java.util.concurrent.Callable;

public class Test3<V> implements Callable<V> {

	@Override
	public V call() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

}

Myrunnable:

import java.text.SimpleDateFormat;
import java.util.Date;

public class MyRunnable implements Runnable {

	// 写的案例:售票
	int ticker = 50;
	SimpleDateFormat dateFormat = null;

	@Override
	public void run() {
		// TODO Auto-generated method stub

		dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSSS");

		while (ticker > 0) {
			// 所有线程都是公共的,而且是不可变的
//			synchronized (MyRunnable.class) {
//				if (ticker > 0) {
//					ticker--;
//					System.out.println(Thread.currentThread().getName() + "售出一张票,剩余" + ticker + "张,"
//							+ dateFormat.format(new Date()));
//
//				}
//			}
			maipiao();

		}
	}

	synchronized public void maipiao() {
		if (ticker > 0) {
			ticker--;
			System.out.println(
					Thread.currentThread().getName() + "售出一张票,剩余" + ticker + "张," + dateFormat.format(new Date()));

		}
	}
}

Test4:实现runnable的类

public class Test4 {

	public static void main(String[] args) {
		// 创建三个卖票窗口
		MyRunnable target = new MyRunnable();

		// runnable 是怎么启动线程的
		Thread thread1 = new Thread(target);// 1号窗口
		Thread thread2 = new Thread(target);// 2号窗口
		Thread thread3 = new Thread(target);// 3号窗口

		// 在MyRUnnable中的ticker票池,对于thread1、2、3是公共的吗,是的,因为使用的是同一对象
		// runnable更容易实现数据共享,但是不会解决数据不安全的问题。
		thread1.start();
		thread2.start();
		thread3.start();
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值