다중 루틴 생성의 두 가지 방식과 루틴 동기화 문제 실례

3083 단어
문제1: 스레드를 만드는 두 가지 방법:
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("      ");
		}
	}
}

문제2: 스레드 동기화 문제
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()+"         ——  ");
	}
}

좋은 웹페이지 즐겨찾기