第七章多线程编程
7.1奇偶序列线程,继承Thread类
public class NumberThread extends Thread {
private int first,n;
public NumberThread(String name,int first,int n)
{
super(name);
this.first = first;
this.n = n;
}
public void run()
{
long time1 = System.currentTimeMillis();
System.out.print("\n"+ this.getName()+"开始时间="+time1+", ");
for(int i=0;i<n;i++)
{
System.out.print((first+2*i)+" ");
}
long time2 = System.currentTimeMillis();
System.out.println(this.getName()+" 结束时间="+time2+", 耗时"+(time2-time1) + "毫秒。 ");
}
public static void main(String args[]) {
System.out.println("currentThread="+Thread.currentThread().getName());
Thread thread_odd = new NumberThread("奇数进程",1,20);
Thread thread_even = new NumberThread("偶数进程",2,10);
thread_odd.start();
thread_even.start();
System.out.println("activeCount="+Thread.activeCount());
}
}
运行结果
7.2奇偶序列线程,接口Runnable
public class NumberRunnable implements Runnable {
private int first,end;
public NumberRunnable(int first,int end) {
this.first =first;
this.end = end;
}
public void run() {
for(int i =first;i<end;i++)
System.out.print(i+" ");
System.out.println("结束! ");
}
public static void main(String args[]) {
Runnable target = new NumberRunnable(1,20);
Thread thread_odd = new Thread(target,"奇数进程");
thread_odd.start();
new Thread(new NumberRunnable(2,10),"偶数进程").start();
}
}
运行结果
7.3滚动字
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class WelcomeJFrame extends JFrame {
public WelcomeJFrame(String[] texts) {
super("滚动字");
this.setBounds(300,300,740,300);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
if(texts == null||texts.length == 0)
this.getContentPane().add(new RollbyJPanel("Welcome!"));
else
{
this.getContentPane().setLayout(new GridLayout(texts.length,1));
for(int i=0;i<texts.length;i++)
{
this.getContentPane().add(new RollbyJPanel(texts[i]));
}
}
this.setVisible(true);
}
public WelcomeJFrame() {
this(null);
}
private class RollbyJPanel extends JPanel implements ActionListener,Runnable
{
JTextField text_word,texts[];//文本控件
JButton[] buttons;//按钮控件
Thread thread; //线程对象
int sleeptime; //线程睡眠时间
Font font = new Font("宋体",1,20); //设置字体大小和格式
public RollbyJPanel(String text)
{
this.setLayout(new GridLayout(2,1));
this.text_word = new JTextField(String.format("%65s", text)); //text后加空格字符串
this.add(this.text_word);
this.text_word.setFont(font);
//创建面板
JPanel cmdpanel = new JPanel();
this.add(cmdpanel);
String[] textstr= {"sleeptime","State1","State2","isAlive"};
this.texts = new JTextField[textstr.length];
for(int i=0;i<this.texts.length;i++)
{
cmdpanel.add(new JLabel(textstr[i]));
cmdpanel.add(this.texts[i] = new JTextField(8));
this.texts[i].setEditable(false); // 设置文本行不可编辑
}
this.sleeptime = (int)(Math.random()*100);
this.texts[0].setText(""+sleeptime);
this.texts[0].setEditable(true);
this.texts[0].addActionListener(this);
String[] buttonstr = {"启动","中断"};
this.buttons = new JButton[buttonstr.length];
for(int i=0;i<this.buttons.length;i++)
{
cmdpanel.add(this.buttons[i]= new JButton(buttonstr[i]));
this.buttons[i].addActionListener(this);
}
this.buttons[1].setEnabled(false); //设置中断按钮为无效状态
this.thread = new Thread(this);
this.texts[1].setText(""+this.thread.getState()); //线程状态文本行
this.texts[3].setText(""+this.thread.isAlive());
}
public void run() {
while(true) {
try
{
String str = this.text_word.getText();
this.text_word.setText(str.substring(1)+ str.substring(0,1)); //substring方法返回一个子字符串从指定索引
Thread.sleep(this.sleeptime);
}
catch(InterruptedException ex)
{
break;
}
}
}
public void actionPerformed(ActionEvent event)
{
if(event.getSource() == this.texts[0])
{
try
{
this.sleeptime= Integer.parseInt(this.texts[0].getText());
}
catch(NumberFormatException ex)
{
JOptionPane.showMessageDialog(this, "\""+this.texts[0].getText()+"\" 不能转换成整数,请重新输入!");
}
}
else if(event.getSource() == this.buttons[0])
{
if(this.thread.getState() != Thread.State.NEW)
this.thread = new Thread(this);
this.thread.start();
this.texts[1].setText(""+this.thread.getState()); //线程启动后进入Runnable态
this.buttons[0].setEnabled(false);
this.buttons[1].setEnabled(true);
//下句相邻显示,线程睡眠态
this.texts[2].setText(""+this.thread.getState());
}
else if(event.getSource() == this.buttons[1])
{
this.thread.interrupt();
this.texts[1].setText(""+this.thread.getState());
this.buttons[0].setEnabled(true);
this.buttons[1].setEnabled(false);
this.texts[2].setText(""+this.thread.getState());
}
this.texts[3].setText(""+this.thread.isAlive());
}
}
public static void main(String arg[]) {
String texts[] = {"Welcome","Hello","Rolly"};
new WelcomeJFrame(texts);
}
}
运行结果
7.4银行账户类
public class Account {
String name;
double balance;
public Account(String name) {
this.name = name;
this.balance = 0;
}
public void put(double value)
{
if(value >0 )
{
this.balance +=value;
}
}
public double get(double value)
{
if(value <= 0)
{
return 0;
}
if(value <= this.balance)
this.balance -= value;
else
{
value = this.balance;
this.balance = 0 ;
}
return value;
}
public static void main(String args[]) {
Account wang = new Account("Wang");
(new SaveThread(wang,100)).start();
(new SaveThread(wang,200)).start();
(new FetchThread(wang,300)).start();
(new SaveThread(new Account("Li"),100)).start();
}
}
class SaveThread extends Thread{
private Account account;
private double value;
public SaveThread(Account account,double value)
{
this.account = account;
this.value = value;
}
public void run()
{
double howmatch =this.account.balance;
this.account.put(this.value);
//sleep(1)
System.out.println(this.getClass().getName()+", "+this.account.name+"账户, 现有"+howmatch+",存入"+this.value+",余额"+this.account.balance);
}
}
class FetchThread extends Thread
{
private Account account;
private double value;
public FetchThread(Account account,double value)
{
this.account = account;
this.value = value;
}
public void run () {
double howmatch = this.account.balance;
//sleep(1)
System.out.println(this.getClass().getName()+", "+this.account.name+"账户, 现有"+howmatch+", 取走"+this.account.get(this.value)+",余额"+this.account.balance);
}
}
运行结果
7.4交互线程的互斥实现
package xiancheng;
public class LockedSaveThread extends Thread{
private Account account;
private double value;
public LockedSaveThread(Account account,double value)
{
this.account = account;
this.value = value;
}
public void run()
{
synchronized(this.account)
{
double howmatch = this.account.balance;
try
{
Thread.sleep(1);
}
catch(InterruptedException ex) {}
this.account.put(this.value);
System.out.println(this.getClass().getName()+", "+this.account.name+"账户, 现有"+howmatch+",存入"+this.value+",余额"+this.account.balance);
}
}
}
class LockedFetchThread extends Thread
{
private Account account;
private double value;
public LockedFetchThread(Account account,double value)
{
this.account = account;
this.value = value;
}
public void run()
{
synchronized(this.account)
{
double howmatch = this.account.balance;
try
{
Thread.sleep(1);
}
catch(InterruptedException ex) {}
this.account.put(this.value);
System.out.println(this.getClass().getName()+", "+this.account.name+"账户, 现有"+howmatch+", 取走"+this.account.get(this.value)+",余额"+this.account.balance);
}
}
}
运行结果
7.6线程通信
public class LockedBuffer<T>
{
private T obj;
public synchronized void put(T obj)
{
this.obj = obj;
}
public synchronized T get()
{
return this.obj;
}
public static void main(String args[])
{
LockedBuffer<Integer> buffer = new LockedBuffer<Integer>();
Integer[] objs = {1,2,3,4};
Thread sender = new SendThread1(objs,buffer);
sender.start();
Thread receiver = new ReceiveThread1(buffer);
receiver.setPriority(sender.getPriority()-1);
receiver.start();
}
}
class SendThread1<T> extends Thread
{
private LockedBuffer<T> buffer;
private T[] objs;
public SendThread1(T[] objs,LockedBuffer<T> buffer)
{
this.objs = objs;
this.buffer = buffer;
}
public void run()
{
for(int i=0;i<this.objs.length;i++)
{
buffer.put(this.objs[i]);
System.out.println(this.getClass().getName()+" put : "+this.objs[i]);
}
buffer.put( null);
System.out.println(this.getClass().getName()+"put : null");
}
}
class ReceiveThread1<T> extends Thread
{
private LockedBuffer<T> buffer;
public ReceiveThread1(LockedBuffer<T> buffer)
{
this.buffer = buffer;
}
public void run()
{
T obj;
do
{
obj = this.buffer.get();
System.out.println("\t\t\t\t"+this.getClass().getName()+" get : "+obj);
}
while(obj!=null);
}
}
运行结果