为了确保在任何时间点一个共享的资源只能被一个线程使用,使用了“同步”。
一、使用同步方法
package sort;
public class Timer {
private static int num=0;
public synchronized void add(String name){
num++;
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(name+"你是第 "+num+" 个使用timer的线程");
}
}
package test;
import sort.Timer;
public class TestRunnable implements Runnable{
Timer timer = new Timer();
@Override
public void run() {
timer.add(Thread.currentThread().getName());
}
public static void main(String[] args) {
TestRunnable testRunnable = new TestRunnable();
Thread t1 = new Thread(testRunnable);
Thread t2 = new Thread(testRunnable);
t1.setName("t1");
t2.setName("t2");
t1.start();
t2.start();
}
}
二、使用同步代码块
package sort;
public class Timer {
private static int num = 0;
public void add(String name) {
synchronized (this) {
num++;
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(name + "你是第 " + num + " 个使用timer的线程");
}
}
}
package test;
import sort.Timer;
public class TestRunnable implements Runnable{
Timer timer = new Timer();
@Override
public void run() {
timer.add(Thread.currentThread().getName());
}
public static void main(String[] args) {
TestRunnable testRunnable = new TestRunnable();
Thread t1 = new Thread(testRunnable);
Thread t2 = new Thread(testRunnable);
t1.setName("t1");
t2.setName("t2");
t1.start();
t2.start();
}
}
两种方式运行的结果:
实现多线程同步的两种方式的优缺点:
- Synchronized方法
优点:可以显示的知道哪些方法是被synchronized关键字保护的
缺点:
—1.方法中有些内容是不需要同步的,如果该方法执行会花很长时间,那么其他人就会花较多时间等待锁被归还;
—2.只能取得自己对象的锁,有时候程序设计的需求,可能会需要其他对象的锁。
- Synchronized代码块
优点:
—1.可以针对某段程序代码同步,不需要浪费时间在别的程序代码上;
—2.可以取得不同对象的锁。
缺点:无法显示的得知哪些方法是被synchronized关键字保护的。