多线程--打印十次"我爱你"
2021-05-16 00:29
标签:you 操作 ++ exception lov str ant for 运行 第一种方式:Lock锁 Thread A=new Thread(new Runnable(){ while(state lock.lock(); Thread B=new Thread(new Runnable(){ while(state lock.lock(); Thread C=new Thread(new Runnable(){ while(state lock.lock(); A.start(); } } 第二种:synchronized同步方法: 具体代码如下: private String word;//线程要打印的字 public void run() { public ThreadDemo2(String word, Object prev, Object current) { public class TestThreadDemo2 { 运行结果: 多线程--打印十次"我爱你" 标签:you 操作 ++ exception lov str ant for 运行 原文地址:https://www.cnblogs.com/twqwe/p/9750004.htmlpackage 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();
public void run(){
if(state%3==0){
System.out.println("我");
state ++;
}
lock.unlock();
}
}
});
public void run(){
if(state%3==1){
System.out.println("爱");
state ++;
}
lock.unlock();
}
}
});
public void run(){
if(state%3==2){
System.out.println("你");
state ++;
}
lock.unlock();
}
}
});
B.start();
C.start();
运行结果如下:package com.test;
public class ThreadDemo2 implements Runnable{
//三个变量 三条线程之间切换执行 一把锁是不够的 2把锁把锁 对象有锁的定义 Object对象
private Object prev;//当前线程的上一个线程要持有的锁
private Object current;//当前线程所要持有的锁
for(int i=0;i synchronized (prev){
synchronized (current){
System.out.println(word);
current.notify();
}
try {
prev.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
this.word = word;
this.prev = prev;
this.current = current;
}
//打印字的操作
}
测试类:package com.test;
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();
}
}