1. 程式人生 > >多線程--打印十次"我愛你"

多線程--打印十次"我愛你"

ble nal 同步方法 多線程 unlock new ack new t ron

第一種方式:Lock鎖

package com.test;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ThreadDemo {
private static int state=0;
public static void main(String[] args) {
final Lock lock=new ReentrantLock();

Thread A=new Thread(new Runnable(){
public void run(){

while(state<=27){
lock.lock();
if(state%3==0){
System.out.println("我");
state ++;
}
lock.unlock();
}
}
});

Thread B=new Thread(new Runnable(){
public void run(){

while(state<=27){
lock.lock();
if(state%3==1){
System.out.println("愛");
state ++;
}
lock.unlock();
}
}
});

Thread C=new Thread(new Runnable(){
public void run(){

while(state<=27){
lock.lock();
if(state%3==2){
System.out.println("你");
state ++;
}
lock.unlock();
}
}
});

A.start();
B.start();
C.start();

}

}
運行結果如下:

技術分享圖片

第二種:synchronized同步方法:

具體代碼如下:

package com.test;
public class ThreadDemo2 implements Runnable{


//三個變量 三條線程之間切換執行 一把鎖是不夠的 2把鎖把鎖 對象有鎖的定義 Object對象

private String word;//線程要打印的字
private Object prev;//當前線程的上一個線程要持有的鎖
private Object current;//當前線程所要持有的鎖

public void run() {
for(int i=0;i<10;i++){
synchronized (prev){
synchronized (current){
System.out.println(word);
current.notify();
}
try {
prev.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

public ThreadDemo2(String word, Object prev, Object current) {
this.word = word;
this.prev = prev;
this.current = current;
}
//打印字的操作
}


測試類:
package com.test;

public class TestThreadDemo2 {
public static void main(String[]args) throws Exception{
Object a=new Object();
Object b=new Object();
Object c=new Object();
Thread t1=new Thread(new ThreadDemo2("I",c,a));
Thread t2=new Thread(new ThreadDemo2("love",a,b));
Thread t3=new Thread(new ThreadDemo2("you",b,c));
t1.start();;
Thread.sleep(1000);
t2.start();;
Thread.sleep(1000);
t3.start();
}
}

運行結果:

技術分享圖片


多線程--打印十次"我愛你"