Java23线程练习:奇偶数

Posted 码农编程录

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java23线程练习:奇偶数相关的知识,希望对你有一定的参考价值。


1.在子线程中输出1-100之间的偶数,主线程输出1-100之间的奇数

package com.atguigu.test02.homework01;

public class Test01 {
	public static void main(String[] args) {
		new Thread(){
			public void run(){
				for (int i = 0; i <= 100; i+=2) {
					System.out.println("子线程:" + i);
				}
			}
		}.start();		
		for (int i = 1; i <= 100; i+=2) {
			System.out.println("主线程:" + i);
		}
	}
}

2.创建和启动2个子线程,一个打印1-10之间奇数,一个打印1-10之间偶数

package com.atguigu.test03.homework02;
//(1)要求每个线程要么不打印,要么就连续打印5个数,每个数打印间隔500毫秒 。(2)但两个线程不要求交替打印。
public class Test02 {
	public static void main(String[] args) {
		Odd o = new Odd();
		Even e = new Even();		
		o.start();
		e.start();
	}
}

class Odd extends Thread{
	private int num = 1;
	public void run(){
		while(true){
			synchronized (Thread.class) {
				for (int i = 1; i <=5; i++) {
					System.out.println("奇数线程,第"  + i + "个:" + num);
					num += 2;
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}			
		}
	}
}

class Even extends Thread{
	private int num = 0;
	public void run(){
		while(true){
			synchronized (Thread.class) {
				for (int i = 1; i<=5; i++) {
					System.out.println("偶数线程,第"  + i + "个:" + num);
					num += 2;
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
}

在这里插入图片描述

3.创建和启动2个子线程,一个打印奇数,一个打印偶数

package com.atguigu.test05.homework03.copy;
//(1)要求实现交替打印。(2)每个数打印间隔1秒
public class Test03 {
	public static void main(String[] args) {
		MyThread t1 = new MyThread();
		MyThread t2 = new MyThread();		
		t1.start();
		t2.start();
	}
}

class PrintNumber{
	private static int num = 1;	
	public static synchronized void print(){
		try {
			PrintNumber.class.notify();
			System.out.println(Thread.currentThread().getName() + ":" + num);
			num++;
			PrintNumber.class.wait();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

class MyThread extends Thread{
	public void run(){
		while(true){
			PrintNumber.print(); //静态方法
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

在这里插入图片描述

4.使用两个线程循环打印出1~100

package com.itheima.demo01;

class Num {
    int i;
    boolean falg;
}

class TestThread1 {
    public static void main(String[] args) {
        Num num=new Num();
        Thread t1=new Thread(new A(num));
        Thread t2=new Thread(new B(num));
        t1.start();
        t2.start();
    }
}

//1111111111111111111111111111111111111111111111111111111111111111111111
class A implements Runnable{
    private Num num;
    public A(Num num) {
        this.num=num;
    }
    @Override
    public void run() {
        while(num.i<99){
            synchronized(num){

//1111111111111111111111111111111111111111111111111111111111111111111
                if(num.falg){
                    try {
                        num.wait();
                    } catch (InterruptedException e) {}
                }
                num.i++;
                num.falg=true;
                System.out.println(Thread.currentThread().getName()+"-"+num.i);
                num.notify();
            }
        }
    }
}

//1111111111111111111111111111111111111111111111111111111111111111111111
class B implements Runnable{
    private Num num;
    B(Num num){
        this.num=num;
    }
    @Override
    public void run() {
        while(num.i<99){
            synchronized(num){

//11111111111111111111111111111111111111111111111111111111111111111
                if(!num.falg){
                    try {
                        num.wait();
                    } catch (InterruptedException e) {}
                }
                num.i++;
                num.falg=false;
                System.out.println(Thread.currentThread().getName()+"-"+num.i);
                num.notify();
            }
        }
    }
}

在这里插入图片描述

5.使用三个线程循环打印出1~100

package com.itheima.demo01;

class TestThread2 {
    public static void main(String[] args) throws Exception{
        Thread t1 = new Thread(new MyThread1(0));
        Thread t2 = new Thread(new MyThread1(1));
        Thread t3 = new Thread(new MyThread1(2));
        t1.start();
        t2.start();
        t3.start();
    }

    static class MyThread1 implements Runnable {
        private static Object lock = new Object();
        private static int count = 0;
        int no;
        public MyThread1(int no) {
            this.no = no;
        }
        @Override
        public void run() {
            while (true) {
                synchronized (lock) {

//11111111111111111111111111111111111111111111111111111111111111111111
                    if (count >= 100) {
                        break;
                    }
                    if (count % 3 == this.no) {
                        count++;
                        System.out.println(this.no + "--->" + count);
                    } else {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    lock.notifyAll();
                }
            }
        }
    }
}

在这里插入图片描述

6.账户类:synchronized 方法

package com.atguigu.test06.homework04;
/*
  案例:1、创建一个银行账户类:(1)属性:账号,余额。(2)get/set。(3)toString():返回:账户:xxx,余额:xxx
  2、创建一个丈夫类:负责往里存钱,每次存款[0,10000)以内不等
  3、创建一个妻子类:负责取钱,每次取款[0,10000)以内不等,如果余额不足,要等丈夫存够了才能取
*/
public class Test04 {
	public static void main(String[] args) {
		Account a = new Account("1122", 0);
		AccountManager am = new AccountManager(a);
		Husband h = new Husband("崔志恒",am);
		Wife w = new Wife("甄玉禄",am);		
		h.start();
		w.start();
	}
}

//11111111111111111111111111111111111111111111111111111111111111111111111
class Husband extends Thread{
	private AccountManager am;
	public Husband(String name,AccountManager am) {
		super(name);
		this.am = am;
	}
	public void run(){
		while(true){
			am.save();
			try {
				Thread.sleep(5000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

//11111111111111111111111111111111111111111111111111111111111111111111111
class Wife extends Thread{
	private AccountManager am;
	public Wife(String name,AccountManager am) {
		super(name);
		this.am = am;
	}
	public void run(){
		while(true){
			am.withdraw();
			try {
				Thread.sleep(5000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

//11111111111111111111111111111111111111111111111111111111111111111111111
class AccountManager{
	private Account account;	
	public AccountManager(Account account) {
		super();
		this.account = account;
	}
	public synchronized void save(){
		double money = Math.random() * 10000;
		System.out.println(Thread.currentThread().getName() + "开始存钱,目前账户状态:" + account);
		System.out.println("本次存钱的数量是:" + money);
		account.setBalance(account.getBalance() + money);
		System.out.println(Thread.currentThread().getName() +  "存钱结束,目前账户状态: " + account);
		this.notify();
	}	
	public synchronized void withdraw(){
		double money = Math.random() * 10000;
		System.out.println(Thread.currentThread().getName() + "开始取钱,目前账户状态:" + account);
		while(money > account.getBalance()){
			try {
				System.out.println("本次想取钱的数量是:" + money + ",余额不足....");
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		account.setBalance(account.getBalance() - money);
		System.out.println(Thread.currentThread().getName() +  "取钱结束,目前账户状态: " + account);
	}
}

//111111111111111111111111111111111111111111111111111111111111111111111111
class Account{
	private String id;
	private double balance;
	public Account(String id, double balance) {
		super();
		this.id = id;
		this.balance = balance;
	}
	public Account() {
		super();
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public double getBalance() {
		return balance;
	}
	public void setBalance(double balance) {
		this.balance = balance;
	}
	@Override
	public String toString() {
		//账户:xxx,余额:xxx
		return "账户: " + id +"余额:" + balance;
	}	
}

在这里插入图片描述

7.模拟多个人通过一个山洞:synchronized 方法

package com.atguigu.test07.homework05;
/*
​	1、这个山洞每次只能通过一个人,每个人通过山洞的时间为5秒;
​	2、随机生成10个人,同时准备过此山洞
​	3、定义一个变量用于记录通过隧道的人数
​	4、显示每次通过山洞人的姓名,和通过顺序;
 */
public class Test05 {
	public static void main(String[] args) {
		Tunnel t = new Tunnel();		
		for (int i = 1; i <= 10; i++) {
			Thread th = new Thread(t, "p" + i);
			th.start();
		}

以上是关于Java23线程练习:奇偶数的主要内容,如果未能解决你的问题,请参考以下文章

Java 多线程练习

Java两个线程实现交替运行-以交替打印奇偶数为例

java 练习递归..是奇数奇偶校验

java循环练习:1.输出1~100中的所有偶数

JAVA 基础编程练习题44 程序 44 偶数的素数和

Java学习-死锁练习