// 解决并发问题的两种方式:
/*
首先先说什么是并发问题:多个线程共享数据 导致并发错误
根本原因: 多个线程共享同一个对象
直接原因: 线程体当中连续的两行代码未必能够连续执行~
导火线: 时间片耗尽的不是时候(我们却无力控制)
/*
首先先说什么是并发问题:多个线程共享数据 导致并发错误
根本原因: 多个线程共享同一个对象
直接原因: 线程体当中连续的两行代码未必能够连续执行~
导火线: 时间片耗尽的不是时候(我们却无力控制)
临界资源: 多个线程共享的那个对象被称作临界资源
1 synchronized 修饰代码块 / 修饰方法
synchronized(临界资源){} / public synchronized void add(){ ....}
2 java 工具包的并发包的锁包的可重入锁 since jdk 5.0
import java.util.concurrent.locks.ReentrantLock
*/
import java.util.concurrent.locks.*;
public class SolutionConcurrent{
public static void main(String[] args){
Lock lock = new ReentrantLock();
Student stu = new Student("张曼玉", "女士");
PrintThread pt = new PrintThread(stu,lock);
ChangeThread ct = new ChangeThread(stu,lock);
P p = new P();
p.setDaemon(true); // 设置为守护线程
p.setPriority(1); //守护线程通常有较低的优先级
p.start();
// 设置优先级
//pt.setPriority(1)
// 返回主线程
//Thread main = Thread.currentThread();
// 设置线程名称
pt.setName("PrintThread");
ct.setName("ChangeThread");
pt.start();
ct.start();
}
}
class PrintThread extends Thread{
Student stu;
Lock lock;
public PrintThread(Student stu,Lock lock){
this.stu = stu;
this.lock = lock;
}
@Override
public void run(){
while(true){
//synchronized(stu){
lock.lock();
// getName(); 获取线程名称
System.out.println(getName() + stu);
lock.unlock();
//}
}
}
}
class ChangeThread extends Thread{
Student stu;
Lock lock;
public ChangeThread(Student stu,Lock lock){
this.stu = stu;
this.lock = lock;
}
@Override
public void run(){
boolean flag = false;
while(true){
lock.lock();
if(flag){
stu.name = "梁朝伟";
stu.gender = "先生";
}
else{
stu.name = "张曼玉";
stu.gender = "女士";
}
flag = !flag;
lock.unlock();
}
}
}
class Student{
String name;
String gender;
public Student(String name,String gender){
this.name = name;
this.gender = gender;
}
public String toString(){
return name + "" + gender;
}
}
class P extends Thread{
@Override
public void run(){
while(true)
System.out.println("--------我是守护线程-------");
}
}