一、使用synchronized实现同步代码块
格式:
synchronized (对象
){
// 需要被同步的代码;
}
实例:
class MyThread4 implements Runnable{
private int ticket=100;
Integer key=new Integer(10086);
@Override
public void run() {
while(true){
synchronized(key){
if(ticket>0){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+":"+ticket);
ticket--;
}
else
break;
}
}
}
}
public class ThreadTest4 {
public static void main(String[] args) {
MyThread4 myThread4 = new MyThread4();
Thread th1 = new Thread(myThread4);
Thread th2 = new Thread(myThread4);
Thread th3 = new Thread(myThread4);
th1.start();
th2.start();
th3.start();
}
}
二、使用synchronized实现同步方法
格式:
public synchronized void show (String name){
….
}
实例:
class MyThread5 implements Runnable{
private int ticket=100;
@Override
public void run() {
while(true){
show();
if(ticket<=0)
break;
}
}
private synchronized void show() {
if(ticket>0){
System.out.println(Thread.currentThread().getName()+":"+ticket);
ticket--;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class ThreadTest5 {
public static void main(String[] args) {
MyThread5 myt = new MyThread5();
Thread th1=new Thread(myt);
Thread th2=new Thread(myt);
Thread th3=new Thread(myt);
th1.start();
th2.start();
th3.start();
}
}
注意:
1、使用synchronized关键字实现多线程同步的关键是保证其中synchronized(对象)中对象的一致;
2、其中同步方法中无static修饰的对象是当前对象本身(this),有static修饰的是类本身;
三、使用Loct手动实现同步
格式:
class A{
private final ReentrantLock lock = new ReenTrantLock();
public void m(){
lock.lock();
try{
//保证线程安全的代码
;
}
finally{
lock.unlock();
}
}
}
实例:
import java.util.concurrent.locks.ReentrantLock;
class MyThread10 implements Runnable{
private int ticket=100;
private ReentrantLock lock=new ReentrantLock();
@Override
public void run() {
while(true){
try {
lock.lock();
if (ticket > 0) {
System.out.println(Thread.currentThread().getName() + ":" + "售出第" + show()+ "张票成功");
ticket--;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else
break;
} finally {
lock.unlock();
}
}
}
private int show(){
return 101-ticket;
}
}
public class ThreadTest10 {
public static void main(String[] args) {
MyThread10 meh=new MyThread10();
Thread th1=new Thread(meh);
Thread th2=new Thread(meh);
Thread th3=new Thread(meh);
th1.setName("窗口一");
th2.setName("窗口二");
th3.setName("窗口三");
th1.start();
th2.start();
th3.start();
}
}