/*
* 1.同步方法
* synchronized 方法声明
* {
* //方法体
* }
*
* 2.同步块
* synchronized(资源对象)
* {
* //需要进行同步的方法
* }
*
*/
1.代码示例:public class ThreadClass{
public static void main(String args[]) {
Printer pr = new Printer();
Teacher th1 = new Teacher(pr, "Marks", 56, 89, 78);
Teacher th2 = new Teacher(pr, "Hello", 67, 76, 82);
Teacher th3 = new Teacher(pr, "World", 80, 90, 70);
th1.th.start();
th2.th.start();
th3.th.start();
}
}
class Printer {
//方法一.同步方法来实现线程同步
// synchronized void printScore(String name,int score1,int score2,int score3) {
synchronized void printScore(String name,int score1,int score2,int score3) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(name+"的成绩");
System.out.println(name+"英语:"+score1);
System.out.println(name+"数学:"+score2);
System.out.println(name+"语文:"+score3);
}
}
class Teacher implements Runnable {
Printer ps = null;
String name = null;
Thread th;
int score1;
int score2;
int score3;
Teacher(Printer ps,String name,int score1,int score2,int score3) {
this.ps = ps;
this.name =name;
th = new Thread(this);
this.score1 = score1;
this.score2 = score2;
this.score3 = score3;
}
public void run() {
//方法二.使用同步代码块来实现同步;
synchronized (ps) {
ps.printScore(name, score1, score2, score3);
}
}
}
结果:
Marks的成绩
Marks英语:56
Marks数学:89
Marks语文:78
World的成绩
World英语:80
World数学:90
World语文:70
Hello的成绩
Hello英语:67
Hello数学:76
Hello语文:82
2.Java的同步是通过锁的机制来实现
代码示例:
class Source {
//定义同步方法 method1;
synchronized void method1() {
System.out.println("进入方法method1,获得锁");
try {
Thread.sleep(1000); //线程休眠
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("method1方法执行完毕,释放锁");
}
//定义同步方法 method2;
synchronized void method2() {
System.out.println("进入方法method2,获得锁");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("method2方法执行完毕,释放锁");
}
}
class MyThread implements Runnable {
String name;
Source s = null;
MyThread(Source s,String name) {
this.s = s;
this.name = name;
}
public void run() {
if("method1" == name) {
s.method1(); //调用同步方法1
}
else {
System.out.println("Thread2启动...准备调用method2方法");
s.method2(); //调用同步方法2
}
}
}
public class ThreadClass {
public static void main(String args[]) {
Source s = new Source(); //创建一个资源对象
//创建两个实现Runnable接口的对象
MyThread mt1 = new MyThread(s, "method1");
MyThread mt2 = new MyThread(s, "method2");
//创建两个线程
Thread t1 = new Thread(mt1);
Thread t2 = new Thread(mt2);
//启动线程
t1.start();
t2.start();
}
}
结果:
进入方法method1,获得锁
Thread2启动...准备调用method2方法
method1方法执行完毕,释放锁
进入方法method2,获得锁
method2方法执行完毕,释放锁