有关线程编程题集锦

**

线程编程题目:

**
1.编写10个线程,第一个线程从1加到10,第二个线程从11加20…第十个线程从91加到100,最后再把10个线程结果相加。

public class Test01 {
	public static void main(String[] args) throws InterruptedException {
		int result=0;
		for (int i = 0; i <10; i++) {
			Create10 threadCreate10=new Create10();
			threadCreate10.start();
			threadCreate10.join();
			result += threadCreate10.sum + i*10*10;
			System.out.println("第"+(i+1)+"个线程----->"+result);
		}
		System.out.println(Thread.currentThread().getName()+"----->"+result);
	}
	
}
class Create10 extends Thread{
	    int sum=0;
		public void run() {
			for (int i = 1; i <= 10; i++) {
				sum+=i;
			}
		}
	
}

2.创建三个线程,第一个输出a,第二个线程输出b,第三个线程输出c。

    public class ThreadTest {
    	 private static int num=3;
    	public static void main(String[] args) throws InterruptedException {
    		Scanner scanner = new Scanner(System.in);
    	    String cid = scanner.nextLine();
    	    System.out.print(cid);
    		while (true) {
    			if (num>0) {
    	            ThreadJoinTest t1 = new ThreadJoinTest("_A");
    	            ThreadJoinTest t2 = new ThreadJoinTest("_B");
    	            ThreadJoinTest t3 = new ThreadJoinTest("_C");
    			t1.start();
    			/**join方法可以传递参数,join(10)表示main线程会等待t1线程10毫秒,10毫秒过去后,
    			 * main线程和t1线程之间执行顺序由串行执行变为普通的并行执行
    			 */
    			t1.join(10);
    			t2.start();
    			t2.join(10);
    			t3.start();
    			num=-3;
    			}
    		}
    	}
    }

class ThreadJoinTest extends Thread {
	public ThreadJoinTest(String name) {
		super(name);
	}
	@Override
	public void run() {
		System.out.print(this.getName());
	}
}

3.写2个线程,其中一个线程打印1~52,另一个线程打印A~Z,打印顺序应该是12A34B56C…5152Z。

public class Test03{
	 public static void main(String[] args) {
	        Object obj = new Object();
	        new Thread(() -> {
	            synchronized (obj) {
	                int i = 1;
	                while (i <= 52) {
	                    System.out.print(i);
	                    i++;
	                    System.out.print(i);
	                    i++;
	                        obj.notify();
	                        try {
	                            obj.wait();
	                        } catch (InterruptedException e) {
	                            e.printStackTrace();
	                        }
	                    }
	                }
	            
	        }).start();
	 
	        new Thread(() -> {
	            synchronized (obj) {
	                char c = 'A';
	                while (c <= 'Z') {
	                	System.out.print(c++);
	                    obj.notify();
	                    try {
	                        obj.wait();
	                    } catch (InterruptedException e) {
	                        e.printStackTrace();
	                    }
	                }
	            }
	        }).start();
	    }
}

4.编程实现如下效果:在主线程 main 中,创建线程 thread1 ,且 main 以及 thread1 都会打印一条输出,要求每次执行程序时 thread1 的输出都一定在 main 线程之前,使用语言不限。

public class Test04 {
		public static void main(String[] args) throws InterruptedException {
			MythreadTest1 mythread=new MythreadTest1();
			mythread.start();
			mythread.join();
			System.out.println("main");
		}
}
class MythreadTest1 extends Thread{
	public void run() {
		System.out.println("thread1");
	}
}

5.设计 4 个线程,其中两个线程每次对 j 增加 1 ,另外两个线程对 j 每次减少 1. 写出程序。

public class Test05 {
   private static int j=0;//定义变量j
    public synchronized static void add(){
        j++;//定义同步方法每次只有一个线程对j进行j++操作
    }
    public synchronized static void dec(){
      j--;//定义同步方法每次只有一个线程对j进行j--操作
    }
   public static void main(String[] args) throws InterruptedException{
         for(int i=0;i<2;i++){
           new Thread(new Runnable(){//使用匿名内部类进行线程的创建,重写run()方法,调用add()方法
            public void run(){
           while(true){
                 add();
                 System.out.println(j);
                
           }
         }
         }).start();
           Thread.sleep(1000);
         new Thread(new Runnable(){//使用匿名内部类进行线程的创建,重写run()方法,调用dec()方法
           public void run(){
              while(true){
                dec();
                System.out.println(j);
           }
          }
        }).start();
        }
   }
}

6.生产者与消费者的线程关系

   public class Test05 {
    	public static void main(String[] args) {   
    		//等待唤醒案例        
    		BaoZi bz = new BaoZi(); 
    		ChiHuo ch = new ChiHuo("吃货",bz);    
    		BaoZiPu bzp = new BaoZiPu("包子铺",bz);    
    		ch.start();     
    		bzp.start();
    		}
    }
    //实体类表示:包子的馅、皮、存在状态
    class BaoZi {
    	String  pier ;   
    	String  xianer ;   
    	boolean  flag = false ;//包子资源 是否存在  包子资源状态
    	
    	public String getPier() {
    		return pier;
    	}
    	public void setPier(String pier) {
    		this.pier = pier;
    	}
    	public String getXianer() {
    		return xianer;
    	}
    	public void setXianer(String xianer) {
    		this.xianer = xianer;
    	}
    	public boolean isFlag() {
    		return flag;
    	}
    	public void setFlag(boolean flag) {
    		this.flag = flag;
    	}
    	
    	
    }
    //消费者
    class ChiHuo extends Thread{  
    	private BaoZi bz;  
    	
    	public ChiHuo(String name,BaoZi bz){   
    		super(name);      
    		this.bz = bz; 
    		}  
    	
    	@Override    
    	public void run() { 
    		while(true){         
    			synchronized (bz){  
    				if(bz.flag == false){//没包子              
    					try {                 
    						bz.wait();         
    						} catch (InterruptedException e) { 
    							e.printStackTrace();             
    							}          
    					}               
    				System.out.println("吃货正在吃"+bz.pier+bz.xianer+"包子");
    				bz.flag = false;  
    				bz.notify();   
    				
    				}     
    			}  
    		}
    	
    	
    }

//生产者
class BaoZiPu extends Thread { 
	private BaoZi bz;  
	public BaoZiPu(String name,BaoZi bz){ 
		super(name);  
		this.bz = bz;  
		}    
	
	@Override   
	public void run() {
		int count = 0;  //造包子       
		while(true){  //同步           
			synchronized (bz){   
				if(bz.flag == true){//包子资源  存在    
					try {                    
						bz.wait();                
						} catch (InterruptedException e) {   
							e.printStackTrace(); 
							}             
					}  
                 // 没有包子  造包子     
				System.out.println("包子铺开始做包子");    
				if(count%2 == 0){                 
					// 冰皮  五仁                
					bz.pier = "冰皮";     
					bz.xianer = "五仁";        
					}else{       
						// 薄皮  牛肉大葱     
						bz.pier = "薄皮";    
						bz.xianer = "牛肉大葱";    
						}            
			        	count++;    
						bz.flag=true;            
						System.out.println("包子造好了:"+bz.pier+bz.xianer);       
	
				      System.out.println("吃货来吃吧");                //唤醒等待线程 (吃货)           
				      bz.notify();        
            }       
          }   
      }
    
}

7.窗口卖票:三个窗口同时进行卖票

public class Test06 {
	public static void main(String[] args) {
		Tickets tickets=new Tickets();
		Thread t1=new Thread(tickets,"窗口1");
		Thread t2=new Thread(tickets,"窗口2");
		Thread t3=new Thread(tickets,"窗口3");
		t1.start();
		t2.start();
		t3.start();
	}
}

class Tickets implements Runnable{
    int tickets=100;
    Object obj=new Object();
	@Override
	public void run() {
		while (true) {
			synchronized (obj) {
			if (tickets>0) {
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				String name=Thread.currentThread().getName();
				System.out.println(name+"正在卖:"+tickets--);
			}
		  }
		}
	}
	
}
发布了47 篇原创文章 · 获赞 7 · 访问量 5878

猜你喜欢

转载自blog.csdn.net/weixin_42227576/article/details/98482854
今日推荐