三个线程打印1-99
跟三个线程打印ABC一样的
public class PrintOneToNineTy {
private final Lock lock = new ReentrantLock();
private final Condition conditionA = lock.newCondition();
private final Condition conditionB = lock.newCondition();
private final Condition conditionC = lock.newCondition();
private static final int Maxnums = 99;
private static int count = 1;
public void threadA()
{
while(count<Maxnums)
{
lock.lock();
try {
if(count%3!=1)
{
conditionA.await();
}
System.out.println(Thread.currentThread().getName()+count);
count++;
if (count > Maxnums) {
break;
}
conditionB.signal();
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
finally {
lock.unlock();
}
}
}
public void threadB()
{
while(count<Maxnums)
{
lock.lock();
try {
if(count%3!=2)
{
conditionB.await();
}
System.out.println(Thread.currentThread().getName()+count);
count++;
if (count > Maxnums) {
break;
}
conditionC.signal();
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
finally {
lock.unlock();
}
}
}
public void threadC()
{
while(count<Maxnums)
{
lock.lock();
try {
if(count%3!=0)
{
conditionC.await();
}
System.out.println(Thread.currentThread().getName()+count);
count++;
if (count > Maxnums) {
break;
}
conditionA.signal();
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
finally {
lock.unlock();
}
}
}
public static void main(String[] args) {
PrintOneToNineTy printOneToNineTy = new PrintOneToNineTy();
Thread threada = new Thread(printOneToNineTy::threadA, "A");
Thread threadb = new Thread(printOneToNineTy::threadB, "B");
Thread threadc = new Thread(printOneToNineTy::threadC, "C");
threada.start();
threadb.start();
threadc.start();
try {
threada.join();
threadb.join();
threadc.join();
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
线程安全的计数器
AtomicInteger、lock、synchronized都行,但是synchronized效率比较低
public class Counter2 {
private int k =0;
public synchronized int get() {
return k;
}
public synchronized int add()
{
k++;
return k;
}
public synchronized int intNum(int num)
{
k+=num;
return k;
}
}