线程两个小例子:
package cn.csdn.hr.thread;
class Account{
private String name;
private int value;
public void put(int i ){
value+=i;
}
public int get(int i ){
if(value>0){
value-=i;
}else{
i=value;
value=0;
}
return i;
}
public int money( ){
return value;
}
}
class Save implements Runnable{
private Account a1;
private int amount;
public Save(Account a1,int amount){
this.a1=a1;
this.amount=amount;
}
@Override
public void run() {
synchronized (a1) {
int k= a1.money();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
a1.put(amount);
System.out.println("现有"+k+"存入"+amount+"剩余"+a1.money());
}
}
}
class Get implements Runnable{
private Account a1;
private int amount;
public Get(Account a1,int amount){
this.a1=a1;
this.amount=amount;
}
@Override
public void run() {
synchronized (a1) {
int k= a1.money();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
a1.put(amount);
System.out.println("现有"+k+"取走"+a1.get(amount)+"剩余"+a1.money());
}
}
}
public class Bank {
/**
* @param args
*/
public static void main(String[] args) {
Account a1=new Account();
new Thread(new Save(a1,100)).start();
new Thread(new Save(a1,200)).start();
new Thread(new Get(a1,100)).start();
}
}
package cn.csdn.hr.thread;
public class Consumer {
/**
* @param args
*/
public static void main(String[] args) {
Res r= new Res();
Input in = new Input(r);
Output out = new Output(r);
Thread t1 = new Thread(in);
Thread t2 = new Thread(out);
t1.start();
t2.start();
}
}
class Res1{
private String name;
private String sex;
private boolean flag;
public synchronized void set(String name, String sex){
if(flag)
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.name= name;
this.sex=sex;
flag=true;
notify();
}
//生产者
class Input implements Runnable{
private Res r;
public Input(Res r) {
this.r = r;
}
@Override
public void run() {
int x = 0;
while(true){
if(x == 0){
set("张三","男");
}else{
set("lisi","nv");
}
x=(x+1)%2;
}
}
public synchronized void out() {
if(!flag)
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(name+" "+sex);
flag=false;
notify();
}
}
}