多线程的思想主要分为以下三种模式:
- 同步代码块
- 同步方法
- 显式锁
同步代码块
就是用的{}将所要就行同步的代码括在一起,并使用synchronized占用一个Object。一个多窗口进行卖票的例子如下,使用了同步方法,就能避免多线程中出现脏数据,保障了数据安全性问题
public class Test1 {
public static void main(String[] args) {
Object o = new Object();
Ticket t = new Ticket(o);
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
}
static class Ticket implements Runnable{
private Object o;
private static int count = 10;
public Ticket(Object o) {
this.o = o;
}
@Override
public void run() {
while (true){
synchronized (o){
if(count>0){
count--;
System.out.println(Thread.currentThread().getName()+"卖票成功,现有票数为:"+count);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}else {
break;
}
}
}
}
}
}
同步方法
就是将上文的同步代码块,封装成一个方法的思路,封装成方法能更好的进行代码的复用,只需要在方法上声明synchronized即可。多个线程,对一个Object进行占有,保障了线程的安全性问题
public class Test {
public static void main(String[] args) {
Ticket t = new Ticket();
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
}
static class Ticket implements Runnable{
private static int count = 10;
@Override
public void run() {
while (true){
boolean flag = sale();
if(!flag){
break;
}
}
}
public static synchronized boolean sale(){
if(count>0){
count--;
System.out.println(Thread.currentThread().getName()+"卖票成功,现有票数为:"+count);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
return true;
}
return false;
}
}
}
这里要特别说明的是,采用的boolean的方式,对一个变量flag进行处理,以便于开始和结束循环。是一个非常值得参考的写法,在下文中的消费者与生产者模型中也有体现。
显式锁
同步代码块和同步方法都是隐式锁,显式锁就是自行调用接口Lock,将锁写在需要进行同步的方法的开始和结束,以保障数据安全
public class Test2 {
public static void main(String[] args) {
Lock lock = new ReentrantLock();
Ticket t = new Ticket(lock);
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
}
static class Ticket implements Runnable{
private Lock lock;
public static int count = 10;
public Ticket(Lock lock) {
this.lock = lock;
}
@Override
public void run() {
while (true){
lock.lock();
if(count>0){
count--;
System.out.println(Thread.currentThread().getName()+"卖票成功,现有票数为:"+count);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}else {
break;
}
lock.unlock();
}
}
}
}
生产者消费者模型
非常重要,以后了解Kafka一定会用的上的~下面举例说明,厨师上菜和服务员端菜的例子,一次生产对应一次消费,没有生产就没有消费,没有消费就没有生产。先写出优化前后不变的class:
public class Cook implements Runnable{
private Food food;
public Cook(Food food) {
this.food = food;
}
@Override
public void run() {
for(int i=0;i<10;i++){
if(i%2==0){
food.setNameAndTaste("麻婆豆腐","麻辣味");
}else {
food.setNameAndTaste("顺德双皮奶","甜味");
}
}
}
}
public class Waiter implements Runnable{
private Food food;
public Waiter(Food food) {
this.food = food;
}
@Override
public void run() {
for(int i=0;i<10;i++){
System.out.print("第"+i+"轮,上菜的");
food.getFood();
}
}
}
public class Main {
public static void main(String[] args) {
Food food = new Food();
Cook cook = new Cook(food);
Waiter waiter = new Waiter(food);
Thread threadCook = new Thread(cook);
Thread threadWaiter = new Thread(waiter);
threadCook.start();
threadWaiter.start();
}
}
只有Food这个class是需要被优化的
下面由从完全没有处理多线程,到第二步处理了多线程,到第三步终于符合消费者生产者模型的思路进行改造:
- 初始的class Food,会生产出脏数据
public class Food {
private String name;
private String taste;
// 当true的时候,为生产者生产,为false时,为消费者消费
// public boolean flag = true;
public void setNameAndTaste(String name,String taste){
this.name = name;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.taste = taste;
}
public void getFood(){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("菜品名为:"+name+";上菜的菜品口味为:"+taste);
}
}
- 第一次改造后的class Food,增加了排队机制(不再有脏数据了),但因为两个class在争夺时间片,所以会可能会导致一次生产,多次消费
public class Food {
private String name;
private String taste;
// 当true的时候,为生产者生产,为false时,为消费者消费
// public boolean flag = true;
public synchronized void setNameAndTaste(String name,String taste){
this.name = name;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.taste = taste;
}
public synchronized void getFood(){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("菜品名为:"+name+";上菜的菜品口味为:"+taste);
}
}
- 终于符合消费者生产者模型的思路进行改造,一次生产,一次消费直到循环结束
public class Food {
private String name;
private String taste;
// 当true的时候,为生产者生产,为false时,为消费者消费
public boolean flag = true;
public synchronized void setNameAndTaste(String name,String taste){
if(flag){
this.name = name;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.taste = taste;
}
flag = false;
this.notifyAll();
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public synchronized void getFood(){
if(!flag){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("菜品名为:"+name+";上菜的菜品口味为:"+taste);
}
flag = true;
this.notifyAll();
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Java线程的6种状态
- 初始(NEW):新创建了一个线程对象,但还没有调用start()方法。
- 运行(RUNNABLE):Java线程中将就绪(ready)和运行中(running)两种状态笼统的称为“运行”。
线程对象创建后,其他线程(比如main线程)调用了该对象的start()方法。该状态的线程位于可运行线程池中,等待被线程调度选中,以获取CPU的使用权,此时处于就绪状态(ready)。就绪状态的线程在获得CPU时间片后变为运行中状态(running)。 - 阻塞(BLOCKED):表示线程阻塞于锁。
- 等待(WAITING):处于这种状态的线程不会被分配CPU执行时间,它们要等待被显式地唤醒,否则会处于无限期等待的状态。
- 超时等待(TIMED_WAITING):该状态不同于WAITING,它可以在指定的时间后自行返回。
- 终止(TERMINATED):表示该线程已经执行完毕。