使用this作为线程对象锁
在所有线程中,相同对象中的synchronized会互斥。
语法结构:
synchronized(this) {
//同步代码
}
或
public synchronized void accessval(int newVal){
//同步代码
}
/**
* 定义程序员类
*/
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();
}
}
}
/**
* 打开电脑的工作线程
*/
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 {
private Programmer p;
public Working2(Programmer p){
this.p = p;
}
@Override
public void run(){
this.p.coding();
}
}
public class TestSyncThread {
public static void main(String[] args){
Programmer p = new Programmer("张三");
new Working1(p).start();
new Working2(p).start();
}
}