多线程创建的两种方式和线程同步问题实例

问题一:线程创建的两种方式:

package jsj.java.exam.test08;

import java.util.Date;

/**
 * 模拟左右手写字。
 * 
 * 请完善程序。
 */
public class Multithreading {

	public static void main(String[] args) {
		// 创建LeftThread 线程
		//Thread left = ________081________;//2
		Thread left=new LeftThread();
		// 用 RightThread 创建线程
		//Thread right = new Thread(________082________);//2
		Thread right = new Thread(new RightThread());
		// 修改线程名称
		left.setName("左手线程");
		right.setName("右手线程");
		
		// TODO 启动两个线程
		//________083________;//1
		//________084________;//1
		left.start();
		right.start();
	}
	
}

//class LeftThread extends ________085________ {//2
class LeftThread extends Thread {

	public void run() {
		for(int i=0; i<10; i++) {
			System.out.println("我是左手线程");
			
		}
	}
}
//class RightThread implements ________086________ {//2
class RightThread implements Runnable {

	public void run() {
		for(int i=0; i<10; i++) {
			System.out.println("我是右手线程");
		}
	}
}

问题二:线程同步问题

package p2.v3;

/*模拟夫妻提款的操作,未使用同步*/
public class HusbandAndWifeStory {
	public static void main(String[] args) {
		BankAccount bankAccount = new BankAccount(3000);
		WithDraw withdraw = new WithDraw(bankAccount);
		Thread husband = new Thread(withdraw);
		Thread wife = new Thread(withdraw);
		husband.setName("HUSBAND");
		wife.setName("    WIFE");
		husband.start();
		wife.start();
		System.out.println("最后银行账户还剩:"+bankAccount.getBalance());

	}

}

class BankAccount {
	private int balance;
	public BankAccount(int balance) {
        this.balance=balance;		
	}

	// 查询余额
	public int getBalance() {
		return balance;
	}

	// 取款
	public void withdraw(int amount) {

		balance = balance - amount;

	}
}

class WithDraw implements Runnable {
	private BankAccount account;

	public WithDraw(BankAccount account) {
		this.account = account;

	}

	@Override
	public void run() {//

		withdDraw();//
	}
	private synchronized void withdDraw(){//
		System.out.println(Thread.currentThread().getName()+"得到了账户的控制权——开始");//
		if (account.getBalance() < 2000) {
			System.out.println(Thread.currentThread().getName()
					+ "在查询时,钱透支了,不够了");
		} else {
			System.out.println(Thread.currentThread().getName()+"在查询时,余额为"+account.getBalance());
			System.out.println(Thread.currentThread().getName()
					+ "准备从账户上取走2000");
			try {
				System.out.println(Thread.currentThread().getName()
						+ "准备休息");
				Thread.sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println(Thread.currentThread().getName() + "醒来");
			account.withdraw(2000);
			System.out.println(Thread.currentThread().getName() + "完成提款");
			System.out.println("现在账户上还剩" + account.getBalance() + "元");			
		}
		System.out.println(Thread.currentThread().getName()+"释放了账户的控制权——结束");
	}
}


你可能感兴趣的:(多线程创建的两种方式和线程同步问题实例)