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。
4、synchronized 和 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();
}
}