package bao9;
/**
* 第4章多线程 4.编写一个程序,创建两个线程对象,每个线程输出1~5的数。
* 要求线程类分别使用继承Thread类和实现Runnable接口两种方式创建。
*
*/
public class Demo1 extends Thread implements Runnable {
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + ":" + (i + 1));
}
}
* 第4章多线程 4.编写一个程序,创建两个线程对象,每个线程输出1~5的数。
* 要求线程类分别使用继承Thread类和实现Runnable接口两种方式创建。
*
*/
public class Demo1 extends Thread implements Runnable {
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + ":" + (i + 1));
}
}
}
package bao9;
import bao1.MyRunnable;
/**
*
* @author 123123 测试类
*/
public class Test {
*
* @author 123123 测试类
*/
public class Test {
public static void main(String[] args) {
// 1.创建 对象起名 ,线路A
MyRunnable myRunnable = new MyRunnable();
Thread t2 = new Thread(myRunnable);
t2.setName("线路A:");
t2.start();
// 1.创建 对象起名 ,线路A
MyRunnable myRunnable = new MyRunnable();
Thread t2 = new Thread(myRunnable);
t2.setName("线路A:");
t2.start();
// 2.创建 对象起名 ,线路B
Thread t1 = new Thread(new MyRunnable(), "线程B:");
t1.setPriority(Thread.MAX_PRIORITY);
t1.start();
Thread t1 = new Thread(new MyRunnable(), "线程B:");
t1.setPriority(Thread.MAX_PRIORITY);
t1.start();
}
}
package bao9;
/**
* 第4章多线程 5.张三和他妻子各拥有一张银行卡和存折,可以对同一个银行账户进行存款的操作。
* 现银行账户中余款为500元,每人各取款五次,每次取款100元,在取款过程中存在网络延迟时。要求使用多线程模拟这个过程。
*
*/
public class Withdraw implements Runnable {
private int balance = 500; // 银行账户余额
private int money = 100; // 每次取款
* 第4章多线程 5.张三和他妻子各拥有一张银行卡和存折,可以对同一个银行账户进行存款的操作。
* 现银行账户中余款为500元,每人各取款五次,每次取款100元,在取款过程中存在网络延迟时。要求使用多线程模拟这个过程。
*
*/
public class Withdraw implements Runnable {
private int balance = 500; // 银行账户余额
private int money = 100; // 每次取款
public void run() {
while (true) {
synchronized (this) {
if (balance <= 0) {
break;
}
// 修改数
balance -= money;
while (true) {
synchronized (this) {
if (balance <= 0) {
break;
}
// 修改数
balance -= money;
// 设置网络延迟为05秒
try {
Thread.sleep(500); // 500毫秒=0.5秒
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 显示信息
System.out.println(Thread.currentThread().getName() + "准备取款");
System.out.println(Thread.currentThread().getName() + "完成取款");
}
}
if (balance == 0) {
System.out.println("余额不足已支付" + Thread.currentThread().getName() + "的取款,余额为" + balance);
}
try {
Thread.sleep(500); // 500毫秒=0.5秒
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 显示信息
System.out.println(Thread.currentThread().getName() + "准备取款");
System.out.println(Thread.currentThread().getName() + "完成取款");
}
}
if (balance == 0) {
System.out.println("余额不足已支付" + Thread.currentThread().getName() + "的取款,余额为" + balance);
}
}
}
package bao9;
public class Test2 {
public static void main(String[] args) {
Withdraw wd = new Withdraw();
Thread te1 = new Thread(wd,"张三");
Thread te2 = new Thread(wd,"张三的妻子");
te1.start();
te2.start();
Withdraw wd = new Withdraw();
Thread te1 = new Thread(wd,"张三");
Thread te2 = new Thread(wd,"张三的妻子");
te1.start();
te2.start();
}
}