|
项目 |
内容 |
|
这个作业属于哪个课程 |
<任课教师博客主页链接> https://www.cnblogs.com/nwnu-daizh/ |
|
这个作业的要求在哪里 |
<作业链接地址> https://www.cnblogs.com/nwnu-daizh/p/12073034.html |
|
作业学习目标 |
(1) 理解和掌握线程的优先级属性及调度方法; (2) 掌握线程同步的概念及实现技术; (3) Java线程综合编程练习 |
第一部分:总结线程同步技术(10分)
中断线程
(1)当线程的run方法执行方法体中最后一条语句后, 或者出现了在run方法中没有捕获的异常时,线 程将终止,让出CPU使用权。
(2)调用interrupt()方法也可终止线程。 void interrupt() – 向一个线程发送一个中断请求,同时把这个线 程的“interrupted”状态置为true。
(3)Java提供了几个用于测试线程是否被中断的方法。
static boolean interrupted() – 检测当前线程是否已被中断 , 并重置状态 “interrupted”值为false。
boolean isInterrupted() – 检测当前线程是否已被中断 , 不改变状态 “interrupted”值 。
线程状态
(1)利用各线程的状态变换,可以控制各个线程轮流 使用CPU,体现多线程的并行性特征。
(2)线程有如下7种状态: ➢ New (新建) ➢ Runnable (可运行) ➢ Running(运行) ➢ Blocked (被阻塞) ➢ Waiting (等待) ➢ Timed waiting (计时等待) ➢ Terminated (被终止)

(3)其他判断和影响线程状态的方法:
➢join():等待指定线程的终止。
➢join(long millis):经过指定时间等待终止指定 的线程。
➢isAlive():测试当前线程是否在活动。
➢yield():让当前线程由“运行状态”进入到“就 绪状态” ,从而让其它具有相同优先级的等待线程 获取执行权。
多线程调度
(1)Java提供一个线程调度器来监控程序启动后进入 可运行状态的所有线程。线程调度器按照线程的 优先级决定应调度哪些线程来执行。
(2)Java 的线程调度采用优先级策略:
➢ 优先级高的先执行,优先级低的后执行;
➢ 多线程系统会自动为每个线程分配一个优先级,缺省 时,继承其父类的优先级;
➢ 任务紧急的线程,其优先级较高;
➢ 同优先级的线程按“先进先出”的队列原则;
(3)调用setPriority(int a)重置当前线程的优先级, a 取值可以是前述的三个静态量。
调用getPriority()获得当前线程优先级。
(4)下面几种情况下,当前运行线程会放弃CPU: – 线程调用了yield() 或sleep() 方法;
– 抢先式系统下,有高优先级的线程参与调度;
– 由于当前线程进行I/O访问、外存读写、等待用 户输入等操作导致线程阻塞;或者是为等候一 个条件变量,以及线程调用wait() 方法。
线程同步
(1)多线程并发运行不确定性问题解决方案:引入线 程同步机制,使得另一线程要使用该方法,就只 能等待
(2)在Java中解决多线程同步问题的方法有两种:
解决方案一:锁对象与条件对象
用ReentrantLock保护代码块的基本结构如下: myLock.lock();
try { critical section }
finally{ myLock.unlock(); }
(3)解决方案二: synchronized关键字
synchronized关键字作用: ➢ 某个类内方法用synchronized 修饰后,该方 法被称为同步方法;
➢ 只要某个线程正在访问同步方法,其他线程欲要访问同步方法就被阻塞,直至线程从同步方法返回前唤醒被阻塞线程,其他线程方可能进入同步方法。
(4)在同步方法中使用wait()、notify 和notifyAll()方法
一个线程在使用的同步方法中时,可能根据问题 的需要,必须使用wait()方法使本线程等待,暂 时让出CPU的使用权,并允许其它线程使用这个 同步方法。
线程如果用完同步方法,应当执行notifyAll()方 法通知所有由于使用这个同步方法而处于等待的 线程结束等待。
第二部分:实验部分
实验1:测试程序1(5分)
在Elipse环境下调试教材651页程序14-7,结合程序运行结果理解程序;
掌握利用锁对象和条件对象实现的多线程同步技术。
package synch;
import java.util.*;
import java.util.concurrent.locks.*;
/**
* 用于序列化访问的用户锁
* @version 1.30 2004-08-01
* @author Cay Horstmann
*/
public class Bank
{
private final double[] accounts;
private Lock bankLock;
private Condition sufficientFunds;
/**
* Constructs the bank.
* @param n the number of accounts
* @param 每个账户的初始余额
*/
public Bank(int n, double initialBalance)
{
accounts = new double[n];
Arrays.fill(accounts, initialBalance);
bankLock = new ReentrantLock();
sufficientFunds = bankLock.newCondition();
}
/**
* 把一个账户里的钱转到另外一个账户.
* @param from the account to transfer from
* @param to the account to transfer to
* @param amount the amount to transfer
*/
public void transfer(int from, int to, double amount) throws InterruptedException
{//当线程在活动之前或活动期间处于正在等待、休眠或占用状态且该线程被中断时,抛出该异常
bankLock.lock();
try
{
while (accounts[from] < amount)
sufficientFunds.await();//当前线程在接到信号或被中断之前一直处于等待状态
System.out.print(Thread.currentThread());
accounts[from] -= amount;
System.out.printf(" %10.2f from %d to %d", amount, from, to);
accounts[to] += amount;
System.out.printf(" Total Balance: %10.2f%n", getTotalBalance());
sufficientFunds.signalAll();//解除该条件下的等待集中的所有线程的阻塞状态
}
finally
{
bankLock.unlock();//释放锁
}
}
/**
* 得所有账户钱的总和的平均
* @return the total balance
*/
public double getTotalBalance()
{
bankLock.lock();
try
{
double sum = 0;
for (double a : accounts)
sum += a;
return sum;
}
finally
{
bankLock.unlock();//释放锁
}
}
/**
* Gets the number of accounts in the bank.
* @return the number of accounts
*/
public int size()//获取银行中的帐户编号
{
return accounts.length;
}
}
package synch;
/**
* 当多个线程访问一个数据结构时,这个程序显示数据损坏
* @version 1.31 2015-06-21
* @author Cay Horstmann
*/
public class SynchBankTest
{
public static final int NACCOUNTS = 100;
public static final double INITIAL_BALANCE = 1000;
public static final double MAX_AMOUNT = 1000;
public static final int DELAY = 10;
public static void main(String[] args)
{
Bank bank = new Bank(NACCOUNTS, INITIAL_BALANCE);
for (int i = 0; i < NACCOUNTS; i++)
{
int fromAccount = i;
Runnable r = () -> {
try
{
while (true)
{
int toAccount = (int) (bank.size() * Math.random());
double amount = MAX_AMOUNT * Math.random();
bank.transfer(fromAccount, toAccount, amount);
Thread.sleep((int) (DELAY * Math.random()));//休眠时长
}
}
catch (InterruptedException e)
{
}
};
Thread t = new Thread(r);
t.start();
}
}
}

实验1:测试程序2(5分)
在Elipse环境下调试教材655页程序14-8,结合程序运行结果理解程序;
掌握synchronized在多线程同步中的应用。
package synch2;
import java.util.*;
/**
* A bank with a number of bank accounts that uses synchronization primitives.
* @version 1.30 2004-08-01
* @author Cay Horstmann
*/
public class Bank
{
private final double[] accounts;
/**
* Constructs the bank.
* @param n the number of accounts
* @param 每个账户的初始余额
*/
public Bank(int n, double initialBalance)
{
accounts = new double[n];
Arrays.fill(accounts, initialBalance);
}
/**
*把一个账户里的钱转到另外一个账户
* @param from the account to transfer from
* @param to the account to transfer to
* @param amount the amount to transfer
*/
public synchronized void transfer(int from, int to, double amount) throws InterruptedException
{//当线程在活动之前或活动期间处于正在等待、休眠或占用状态且该线程被中断时,抛出该异常
while (accounts[from] < amount)
wait();
System.out.print(Thread.currentThread());
accounts[from] -= amount;
System.out.printf(" %10.2f from %d to %d", amount, from, to);
accounts[to] += amount;
System.out.printf(" Total Balance: %10.2f%n", getTotalBalance());
notifyAll();//随机选择一个在该对象调用wait方法的线程,解除其阻塞状态
}
/**
*得所有账户钱的总和的平均.
* @return the total balance
*/
public synchronized double getTotalBalance()
{
double sum = 0;
for (double a : accounts)
sum += a;
return sum;
}
/**
* Gets the number of accounts in the bank.
* @return the number of accounts
*/
public int size()//获取银行中的帐户编号
{
return accounts.length;
}
}
package synch2;
/**
* This program shows how multiple threads can safely access a data structure,
* using synchronized methods.
* @version 1.31 2015-06-21
* @author Cay Horstmann
*/
public class SynchBankTest2
{
public static final int NACCOUNTS = 100;
public static final double INITIAL_BALANCE = 1000;
public static final double MAX_AMOUNT = 1000;
public static final int DELAY = 10;
public static void main(String[] args)
{
Bank bank = new Bank(NACCOUNTS, INITIAL_BALANCE);
for (int i = 0; i < NACCOUNTS; i++)
{
int fromAccount = i;
Runnable r = () -> {
try
{
while (true)
{
int toAccount = (int) (bank.size() * Math.random());
double amount = MAX_AMOUNT * Math.random();
bank.transfer(fromAccount, toAccount, amount);
Thread.sleep((int) (DELAY * Math.random()));
}
}
catch (InterruptedException e)
{
}
};
Thread t = new Thread(r);
t.start();
}
}
}

实验1:测试程序3(5分)
import javax.sql.rowset.spi.SyncFactory;
class Cbank
{
private static int s=2000;
public synchronized static void sub(int m)
{
int temp=s;
temp=temp-m;
try {
Thread.sleep((int)(1000*Math.random()));
}
catch (InterruptedException e) { }
s=temp;
System.out.println("s="+s);
}
}
class Customer extends Thread
{
public void run()
{
for( int i=1; i<=4; i++)
Cbank.sub(100);
}
}
public class Thread3
{
public static void main(String args[])
{
Customer customer1 = new Customer();
Customer customer2 = new Customer();
customer1.start();
customer2.start();
}
}

class Cbank
{
private static int s=2000;
public synchronized static void sub(int m)
{
int temp=s;
temp=temp-m;
try {
Thread.sleep((int)(1000*Math.random()));
}
catch (InterruptedException e) { }
s=temp;
System.out.println("s="+s);
}
}
class Customer extends Thread
{
public void run()
{
for( int i=1; i<=4; i++)
Cbank.sub(100);
}
}
public class Thread3
{
public static void main(String args[])
{
Customer customer1 = new Customer();
Customer customer2 = new Customer();
customer1.start();
customer2.start();
}
}
实验2:结对编程练习包含以下4部分(10分)
1) 程序设计思路简述;
2) 符合编程规范的程序代码;
3) 程序运行功能界面截图;
利用多线程及同步方法,编写一个程序模拟火车票售票系统,共3个窗口,卖10张票,程序输出结果类似(程序输出不唯一,可以是其他类似结果)。
Thread-0窗口售:第1张票
Thread-0窗口售:第2张票
Thread-1窗口售:第3张票
Thread-2窗口售:第4张票
Thread-2窗口售:第5张票
Thread-1窗口售:第6张票
Thread-0窗口售:第7张票
Thread-2窗口售:第8张票
Thread-1窗口售:第9张票
Thread-0窗口售:第10张票
import javax.swing.plaf.SliderUI;
public class shou {
public static void main(String[] args) {
Mythread mythread=new Mythread();
Thread t1=new Thread(mythread);
Thread t2=new Thread(mythread);
Thread t3=new Thread(mythread);
t1.start();
t2.start();
t3.start();
}
}
class Mythread implements Runnable{
int t=1;
boolean flag=true;
@Override
public void run() {
while(flag) {
try {
Thread.sleep(500);
}
catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (this) {
if(t<=10) {
System.out.println(Thread.currentThread().getName()+"窗口售:第"+t+"张票");
t++;
}
if(t<0) {
flag=false;
}
}
}
}
}

实验总结:(5分)
本周我们继续学习了与同步线程相关的知识,了解了并发多线程的两种解决方法,一种是锁对象,还有一种是synchronized关键字。还有wait()、notify 和notifyAll()方法。通过各种方法改变线程状态,使得线程运行,等待等。
通过锁对象与条件对象、 synchronized关键字解决多线程同步问题。通过相关程序理解了这部分知识,不太理解的部分也通过别的渠道理解了。希望可以将这部分知识熟练运用。