韩顺平Java36——线程Homework

1.

package threadtest.homework;

import java.util.Scanner;

/**
 * @author 紫英
 * @version 1.0
 * @discription
 */
public class Homework01 {
    public static void main(String[] args) {
        T01 t01 = new T01();
        Thread thread = new Thread(t01);
        thread.start();
        T02 t02 = new T02(t01);
        t02.start();


    }
}

class T01 implements Runnable {
    static boolean loop = true;

    public boolean isLoop() {
        return loop;
    }

    public void setLoop(boolean loop) {
        this.loop = loop;
    }

    @Override
    public void run() {
        while (loop) {
//        for (int i = 0; i < 100; i++) {
//
//        }
            System.out.println((int) (Math.random() * 100));
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
         System.out.println("t01结束!"); } }
class T02 extends Thread { private T01 t; public T02(T01 t) { this.t = t; } @Override public void run() { Scanner scanner = new Scanner(System.in); while (true) { System.out.println("请输入字符(q)来结束线程t01:"); char c = scanner.next().charAt(0); if (c == 'q') { t.setLoop(false); //以通知的方式来结束线程t01 System.out.println("t02结束!"); break; } } } }

 

 

 

  2.

 

 

package threadtest.homework;

/**
 * @author 紫英
 * @version 1.0
 * @discription 10000元两人每次取1000
 */
public class Homework02 {
    public static void main(String[] args) {
        Bank bank = new Bank();
        Thread thread01 = new Thread(bank);
        Thread thread02 = new Thread(bank);
        thread01.start();
        thread02.start();
    }
}

class Bank implements Runnable {
    private static int money = 10000;
    boolean loop = true;

    public void takeMoney() {
        synchronized (this) {
            System.out.println(Thread.currentThread().getName() + "取走了¥1000剩余" + (money -= 1000));
        }

注意这里的this对象锁是非公平锁
try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (money < 1000) {
            System.out.println("余额不足!");
            loop = false;
        }
    }

    @Override
    public void run() {
        while (loop) {
            takeMoney();
        }

    }
}

 

 

posted @ 2022-01-26 16:56  紫英626  阅读(35)  评论(0编辑  收藏  举报

紫英