1. 同步执行使用CountDownLatch作为计数工具;
2. 依次执行使用volatile关键字保证可见性;
3. 交错执行使用Semaphore作为信号量控制;
同步执行案例如下图:
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;
public class ThreadSafeDemo {
public static void main(String[] args) {
CountDownLatch countDownLatch = new CountDownLatch(1);
//生成3个线程打印时间
for(int i =0;i<3;i++){
new Thread(()->{
try{
countDownLatch.await();
System.out.println(System.currentTimeMillis());
Thread.sleep(100);
}catch(Exception e){
e.printStackTrace();
}
}).start();
}
System.out.println(System.currentTimeMillis());
countDownLatch.countDown();
}
}
依次执行代码案例如下图:
public class OrderThreadDemo {
static volatile int ticket = 1;
public static void main(String[] args) {
Thread t1 = new Thread(()->{
while(true){
if(ticket == 1){
try{
Thread.sleep(100);
for(int i =0;i<10;i++){
System.out.println("A"+i);
}
}catch (Exception e){
e.printStackTrace();
}
ticket = 2;
return;
}
}
});
Thread t2 = new Thread(()->{
while(true){
if(ticket == 2){
try{
Thread.sleep(100);
for(int i =0;i<10;i++){
System.out.println("B"+i);
}
}catch (Exception e){
e.printStackTrace();
}
ticket = 3;
return;
}
}
});
Thread t3 = new Thread(()->{
while(true){
if(ticket == 3){
try{
Thread.sleep(100);
for(int i =0;i<10;i++){
System.out.println("C"+i);
}
}catch (Exception e){
e.printStackTrace();
}
ticket = 1;
return;
}
}
});
t1.start();
t2.start();
t3.start();
}
}
交错执行代码案例如下图:
import java.util.concurrent.Semaphore;
public class OrderThreadSempDemo {
private static Semaphore s1 = new Semaphore(1);
private static Semaphore s2 = new Semaphore(1);
private static Semaphore s3 = new Semaphore(1);
public static void main(String[] args) {
try{
//获取许可
s1.acquire();
s2.acquire();
}catch(Exception e){
e.printStackTrace();
}
new Thread(()->{
while(true){
try{
s1.acquire();
}catch (Exception e){
e.printStackTrace();
}
try{
Thread.sleep(500);
}catch (Exception e){
e.printStackTrace();
}
System.out.println("A");
s2.release();
}
}).start();
new Thread(()->{
while(true){
try{
s2.acquire();
}catch (Exception e){
e.printStackTrace();
}
try{
Thread.sleep(500);
}catch (Exception e){
e.printStackTrace();
}
System.out.println("B");
s3.release();
}
}).start();
new Thread(()->{
while(true){
try{
s3.acquire();
}catch (Exception e){
e.printStackTrace();
}
try{
Thread.sleep(500);
}catch (Exception e){
e.printStackTrace();
}
System.out.println("C");
s1.release();
}
}).start();
}
}
|