线程的两种同步方法
在Java中实现线程同步可以使用synchronized关键字,共有两种方法:
- 同步代码块
- 同步方法
(在Java中共有四种代码块:普通代码块、构造块、静态块、同步块)
同步块
import java.util.concurrent.ExecutionException;
class MyThread implements Runnable{
private int ticket = 5;
public void run() {
for(int i = 0; i < 20; i++)
{
//同步块
synchronized (this) {
if(this.ticket > 0) {
//休眠1秒
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+" 卖票,票数 = "+this.ticket--);
}
}
}
}
}
public class TestMain {
public static void main(String[] args) throws InterruptedException, ExecutionException {
MyThread mt = new MyThread();
Thread t1 = new Thread(mt,"线程A");
Thread t2 = new Thread(mt,"线程B");
Thread t3 = new Thread(mt,"线程C");
t1.start();
t2.start();
t3.start();
}
}
同步方法
package testThread;
import java.util.concurrent.ExecutionException;
class MyThread implements Runnable{
private int ticket = 5;
public void run() {
for(int i = 0; i < 20; i++)
{
this.sale(); //调用同步方法
}
}
//同步方法
public synchronized void sale() {
if(this.ticket > 0) {
//休眠0.1秒
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+" 卖票,票数 = "+this.ticket--);
}
}
}
public class TestMain {
public static void main(String[] args) throws InterruptedException, ExecutionException {
MyThread mt = new MyThread();
Thread t1 = new Thread(mt,"线程A");
Thread t2 = new Thread(mt,"线程B");
Thread t3 = new Thread(mt,"线程C");
t1.start();
t2.start();
t3.start();
}
}
总结
同步操作与异步操作相比,异步操作的执行速度要高于同步操作,但是同步操作时数据的安全性较高,属于安全的线程操作。