您现在的位置是:首页 > 正文

两个线程循环交替打印

2024-01-31 00:09:27阅读 0

不加锁,while+boolean变量死循环

 

public class Solution {
	volatile static boolean open=false;
	volatile static int index=0;
	static String s="adasdfsafwfvgs";
	static Thread t1=new Thread(new myRun1(),"线程1");
	static Thread t2=new Thread(new myRun2(),"线程2");
	public static void main(String[] args){
		t1.start();
		t2.start();
	}
	static class myRun1 implements Runnable{
		@Override
		public void run() {
			// TODO Auto-generated method stub
				while(index<s.length()){
					if(open){
						System.out.println(s.charAt(index++)+Thread.currentThread().getName());
						open=false;
					}
					
					}
			}
		
		}
	static class myRun2 implements Runnable{
		@Override
		public void run() {
			// TODO Auto-generated method stub
				while(index<s.length()){
					if(!open){
						System.out.println(s.charAt(index++)+Thread.currentThread().getName());
						open=true;
					}
					}
			}
		
		}		
	}

 

wait+notify

public class Solution2 {
	volatile static boolean open=false;
	volatile static int index=0;
	static String s="adasdfsafwfvgs";
	static Object ob=new Object();
	static Thread t1=new Thread(new myRun1(),"线程1");
	static Thread t2=new Thread(new myRun2(),"线程2");
	public static void main(String[] args){
		t1.start();
		t2.start();
	}
	static class myRun1 implements Runnable{
		@Override
		public void run() {
			// TODO Auto-generated method stub
				while(index<s.length()){
					synchronized (ob) {
					if(open){
						System.out.println(s.charAt(index++)+Thread.currentThread().getName());
						open=false;
					}else{
						ob.notifyAll();
						try {
							ob.wait();
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					}
					
					}
			}
		
		}
	static class myRun2 implements Runnable{
		@Override
		public void run() {
			// TODO Auto-generated method stub
				while(index<s.length()){
					synchronized (ob) {
						if(!open){
							System.out.println(s.charAt(index++)+Thread.currentThread().getName());
							open=true;
						}else{
							ob.notifyAll();
							try {
								ob.wait();
							} catch (InterruptedException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					}
					
					}
			}
		
		}		
}

 

网站文章