package com.hnist.lzn.thread;
import java.io.ObjectInputStream;
/*
多线程顺序打印
ABCABCABC A打10次,B打10次,C打10次
*/
public class threeThread {
static int nums = 0;
static Object object = new Object();
static class A implements Runnable {
int id;
String str;
public A(int id,String s){
this.id = id;
this.str = s;
}
@Override
public void run()
{
synchronized (object)
{
while(nums < 30){
if(nums%3 == id){
System.out.println(str);
nums++;
object.notifyAll();
}else{
try{
object.wait();
}catch (Exception e){
}
}
}
}
}
}
public static void main(String[] args) {
Thread th1 = new Thread(new A(0,"A"));
Thread th2 = new Thread(new A(1,"B"));
Thread th3 = new Thread(new A(2,"C"));
th1.start();
th2.start();
th3.start();
}
}
总结: 需要自己学习的几个:
1.多个线程打印,需要一个static 的静态变量。
2.run()方法下必须加锁,同时才能用notify()不是signal()和await()方法,和wait()方法(需要try catch以下)
加锁的2种方式,类锁和对象锁
(1).synchronized(Test.class){}
(2).Object o = new Object();synchronized(object){}
3.封装一个static的静态内部类,配上id,String,再去构造即可。共享外部的static int nums外部变量。
4.再通过if( nums %3 == id ){ 操作…o.notify() }else{ o.wait() } 这样的唤醒等待机制。
nums%3 的范围就是 0–2 的范围。所以nums的起始值应该为nums = 0; id设置也为0-2.
5.Lock lock = new ReentrantLock();
Condition codi = lock.newCondition(); //拿到等待队列
才有await(),signal()等待唤醒方法。