一、单词的注释
mynchronized:对现在执行的程序进行上锁排序进行 Dameon:守护线程
1.public class SyncDemo4 {
public static void main(String[] args) {
Boo boo = new Boo();
Thread t1 = new Thread(){
public void run(){
boo.mathodA();
}
};
Thread t2 = new Thread(){
public void run(){
boo.mathodB();
}
};
t1.start();
t2.start();
}
}
class Boo {
public synchronized void mathodA() {
Thread t = Thread.currentThread();
System.out.println(t.getName() + "方法A开始执行");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("执行完毕");
}
//此时两个方法都被mynchronized修饰,这样会并列进行
public void mathodB() {
synchronized (Boo.class){
Thread t = Thread.currentThread();
System.out.println(t.getName() + "方法B开始执行");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("执行完毕");}
}
}
2.
public class DaemonThreadDemo {
public static void main(String[] args) {
Thread rose = new Thread("rose"){
public void run(){
for(int i = 0;i<5;i++) {
System.out.println(getName()+":let,me,go");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("啊啊啊啊,噗通!");
}
};
Thread jack = new Thread("jack"){
public void run(){
while (true){
System.out.println(getName()+":you jump,i,jump");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
rose.start();
//守护线程必须设立在线程启动之前,setDaemon为守护线程
jack.setDaemon(true);
jack.start();
}
}



