死锁
public class Test01 {
public static void main(String[] args) {
Tom tom = new Tom();
Alice alice = new Alice();
MyThread mt1 = new MyThread(tom, alice, true);
MyThread mt2 = new MyThread(tom, alice, false);
Thread th1 = new Thread(mt1);
Thread th2 = new Thread(mt2);
th1.start();
th2.start();
}
}
class MyThread implements Runnable {
private Tom tom;
private Alice alice;
boolean flag;
public MyThread(Tom tom, Alice alice, boolean flag) {
this.tom = tom;
this.alice = alice;
this.flag = flag;
}
@Override
public void run() {
if (flag) {
synchronized (tom) {
tom.say();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (alice) {
tom.show();
}
}
} else {
synchronized (alice) {
alice.say();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (tom) {
alice.show();
}
}
}
}
}
class Tom {
public void say() {
System.out.println("给我笔");
}
public void show() {
System.out.println("得到笔");
}
}
class Alice {
public void say() {
System.out.println("给我本子");
}
public void show() {
System.out.println("得到本子");
}
}
ThreadLocal
import java.util.Random;
public class Test03 {
public static void main(String[] args) {
MyThread3 mt=new MyThread3();
Thread th1=new Thread(mt, "线程一");
Thread th2=new Thread(mt, "线程二");
Thread th3=new Thread(mt, "线程三");
Thread th4=new Thread(mt, "线程四");
th1.start();
th2.start();
th3.start();
th4.start();
}
}
class MyThread3 implements Runnable {
private static ThreadLocal<Student> local=new ThreadLocal<Student>();
public Student getStudent(){
Student stu = local.get();
if(stu==null){
stu=new Student();
local.set(stu);
}
return stu;
}
@Override
public void run() {
Random r = new Random();
int age = r.nextInt(100);
Student stu=getStudent();
stu.setAge(age);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "***"
+ stu.getAge());
}
}
synchronized和ThreadLocal区别
import java.util.Random;
public class Test02 {
public static void main(String[] args) {
Student stu=new Student();
MyThread2 mt=new MyThread2(stu);
Thread th1=new Thread(mt, "线程一");
Thread th2=new Thread(mt, "线程二");
th1.start();
th2.start();
}
}
class MyThread2 implements Runnable {
private Student stu;
public MyThread2(Student stu) {
this.stu = stu;
}
@Override
public void run() {
while(true){
Random r = new Random();
int age = r.nextInt(100);
synchronized (stu) {
stu.setAge(age);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "***"
+ stu.getAge());
}
}
}
}
class Student {
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}