每天緊張的學習、複習已經成了一種習慣,今天比較早完成作業,上傳一下,日後自己也可以看看是否有更好的方案。
作業1、打印一句話:老師是個大帥哥! (隔一秒輸出一個字)
作業2、自定義一個同步鎖。
package Day18;
import java.util.ArrayList;
public class Day18 implements Runnable{
Meeting meeting = new Meeting();
public static void main(String[] args) {
/*
//1、打印一句話:老師是個大帥哥! (隔一秒輸出一個字)
String str = "老師是個大帥哥!";
for (int i = 0;i < str.length();i++) {
String substr = str.substring(i,i + 1);
System.out.print(substr);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("");
*/
//2、自定義同步,練習同步鎖。
Day18 day18 = new Day18();
Thread thread1 = new Thread(day18);
Thread thread2 = new Thread(day18);
Thread thread3 = new Thread(day18);
Thread thread4 = new Thread(day18);
Thread thread5 = new Thread(day18);
Thread thread6 = new Thread(day18);
thread1.setName(" 孫悟空 ");
thread2.setName(" 豬八戒 ");
thread3.setName(" 唐 僧 ");
thread4.setName("玉皇大帝 ");
thread5.setName(" 如 來 ");
thread6.setName(" 蜘蛛精 ");
thread3.setPriority(Thread.NORM_PRIORITY + 5);
thread1.start();
thread2.start();
thread3.start();
thread4.start();
thread5.start();
thread6.start();
}
@Override
public void run() {
meeting.getRoom(Thread.currentThread().getName());
// meeting.giveupRoom(Thread.currentThread().getName());
}
}
class Meeting {
int roomnumber = 4;
ArrayList<String> person = new ArrayList<String>();
public void getRoom (String chairman) {
synchronized(this) {
if (this.roomnumber > 0) {
roomnumber -= 1;
try {
Thread.sleep(30);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(chairman + ":您已成功預訂會議室,目前會議室還有" + roomnumber + "間。");
person.add(chairman);
} else {
System.out.println(chairman + ":您預訂遲了,目前已無會議室");
}
}
}
}