使用字符串作为线程对象锁
使用线程在执行synchronized时都会同步。
语法结构:
synchronized("字符串"){
//同步代码
}
/**
* 定义程序员类
*/
class Programmer {
private String name;
public Programmer(String name){
this.name = name;
}
/**
* 打开电脑
*/
synchronized public void computer(){
try{
System.out.println(this.name + "接通电源");
Thread.sleep(500);
System.out.println(this.name + "电脑开机");
Thread.sleep(500);
System.out.println(this.name + "系统启动");
Thread.sleep(500);
System.out.println(this.name + "启动成功");
}catch(InterruptedException e){
e.printStackTrace();
}
}
/**
* 编码
*/
synchronized public void coding(){
try{
System.out.println(this.name + "双击idea");
Thread.sleep(500);
System.out.println(this.name + "idea启动");
Thread.sleep(500);
System.out.println(this.name + "开始写代码");
}catch(InterruptedException e){
e.printStackTrace();
}
}
/**
* 去卫生间
*/
public void wc(){
synchronized("suibian"){
try{
System.out.println(this.name + "开门");
Thread.sleep(500);
System.out.println(this.name + "上厕所");
Thread.sleep(500);
System.out.println(this.name + "冲水");
Thread.sleep(500);
System.out.println(this.name + "关门");
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
/**
* 打开电脑的工作线程
*/
class Working1 extends Thread{
private Programmer p;
public working1(Programmer p){
this.p = p;
}
@Override
public void run(){
this.p.computer();
}
}
/**
* 编写代码的工作线程
*/
class Working2 extends Thread{
priavte Programmer p;
public working2(Programmer p){
this.p = p;
}
@Override
public void run(){
this.p = coding();
}
}
/**
* 去卫生间的线程
*/
class WC extends Thread{
private Programmer p;
public WC(Programmer p){
this.p = p;
}
@Override
public void run(){
this.p.wc();
}
}
public class TestSyncThread{
public static void main(String[] args){
Programmer p = new Programmer("张三");
Programmer p1 = new Programmer("李四");
Programmer p2 = new Programmer("王五");
new WC(p).start();
new WC(p1).start();
new WC(p2).start();
}
}