多线程--打印十次"我爱你"

第一种方式: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();
}
}

运行结果:

 
 

猜你喜欢

转载自www.cnblogs.com/twqwe/p/9750004.html