1.多线程同步
实现多线程
1.基础Thread类
2.实现Runnable接口
2.实现Runnable接口
描述:
1.当多个线程访问 MyThread 这个类方法的时候,一排队的方式去进行访问处理(cpu的分配)
2.一个线程要执行 synchronized 方法修饰的代码:尝试去获取锁,如果拿到锁,则立即去执行。
如果拿不到锁,则会一直不断的尝试去获取这把锁,直到拿到锁为止,多个线程去尝试去获取这
把锁,会形成竞争、排队的问题。
/**
* 多线程001-线程同步(共享)
* Created by liudan on 2017/5/28.
*/
public class MyThread extends Thread {
private int count = 5;
@Override
public synchronized void run() {
count--;
System.err.println("∽"+currentThread().getName()+"count:"+this.count);
}
public static void main(String[] args){
MyThread myThread = new MyThread();
Thread t1 = new Thread(myThread,"myThread-1");
Thread t2 = new Thread(myThread,"myThread-2");
Thread t3 = new Thread(myThread,"myThread-3");
Thread t4 = new Thread(myThread,"myThread-4");
Thread t5 = new Thread(myThread,"myThread-5");
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
}
}
输出∽myThread-1count:4 ∽myThread-2count:3 ∽myThread-3count:2 ∽myThread-4count:1 ∽myThread-5count:0