package cn.sdut.threadclass;
/*
*
* 多线程访问同一资源第二步 : 线程设置 以及线程 线程打印 用synchronized
* 两个线程
* 一个线程输入
* 另一个线程打印
* 但是没有实现 输入一个 打印一个的效果
*/
class Person1{
private String name;
private char sex;
public synchronized void setAttribute(String name , char sex){ //可以去掉 synchronized 查看效果
this.name = name;
try {
Thread.sleep(100); //让线程睡眠 更容易看出问题
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.sex = sex;
}
public synchronized void printAttribute(){ // 可以去掉 synchronized 查看效果
try {
Thread.sleep(100); //让线程睡眠 更容易看出问题
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(this.name +" "+this.sex);
}
}
class In implements Runnable {
private Person1 person = null;
public In(Person1 person){
this.person = person;
}
@Override
public void run() {
for(int i = 0;i<500;i++){
if(i%2==0){
person.setAttribute("柯南", '男');
}else{
person.setAttribute("少司命", '女');
}
}
}
}
class Out implements Runnable {
private Person1 person = null;
public Out(Person1 person){
this.person = person;
}
@Override
public void run() {
for(int i = 0;i<500;i++){
person.printAttribute();
}
}
}
public class ThreadDemo02 {
public static void main(String[] args) {
Person1 person = new Person1();//建立共享
In in = new In(person);
Out out = new Out(person);
Thread t1 = new Thread(in);
Thread t2 = new Thread(out);
t1.start();
t2.start();
}
}