1:同步锁 锁一段代码块和方法
锁代码块:
class Ck {
int piao = 10;
public void sale(String name) {
while ( piao > 0 ) {
synchronized (this) {
if ( piao == 0 ) break;
System.out.println(name + "卖了第" + piao + "张票.");
piao --;
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class TestSyncThis extends Thread
{
private String name;
private Ck ck;
public TestSyncThis(String name, Ck ck) {
this.name = name;
this.ck = ck;
}
@Override
public void run()
{
ck.sale(name);
}
public static void main(String[] args)
{
Ck ck = new Ck();
TestSyncThis t1 = new TestSyncThis("董事长", ck);
TestSyncThis t2 = new TestSyncThis("斌哥", ck);
TestSyncThis t3 = new TestSyncThis("阿乐", ck);
t1.start();
t2.start();
t3.start();
}
}
锁对象:
package com.unplooking.thread.practise;
import java.awt.geom.PathIterator;
import java.util.jar.Attributes.Name;
public class RepeatThreadView extends Thread{
static int ticket=10 ;
private String name;
private static Object obj =new Object();
@Override
public void run() {
sale();
}
public RepeatThreadView( String name) {
this.name = name;
}
private void sale() {
while (ticket>0) {
synchronized (obj ) {
if (ticket==0) {
break;
}
System.out.println(name +"买了第"+ticket+"张票");
ticket--;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
RepeatThreadView r1 =new RepeatThreadView( "小明");
RepeatThreadView r2 =new RepeatThreadView( "小花花");
RepeatThreadView r3 =new RepeatThreadView( "小拜拜");
r1.start();
r2.start();
r3.start();
}
}
2:ReentrantLock锁
package com.unplooking.thread.work;
import java.util.concurrent.locks.ReentrantLock;
class AppleFriend {
int apple = 10;
private ReentrantLock lockTest = new ReentrantLock();
public void eat(String name) {
while (apple > 0) {
lockTest.lock();
if (apple == 0)
break;
System.out.println(name + "吃了第" + apple + "个苹果");
apple--;
lockTest.unlock();
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Apple extends Thread{
private String name;
private AppleFriend appleFriend;
public Apple(String name, AppleFriend appleFriend) {
super();
this.name = name;
this.appleFriend = appleFriend;
}
@Override
public void run() {
appleFriend.eat(name);
}
public static void main(String[] args) {
AppleFriend aF1 = new AppleFriend();
Apple a1= new Apple("shimmer", aF1);
Apple a2= new Apple("CHK", aF1);
Apple a3= new Apple("祝祝", aF1);
a1.start();
a2.start();
a3.start();
}
}