Sample08 t1 = new Sample08(str1, str2); Sample08 t2 = new Sample08(str2, str3); Sample08 t3 = new Sample08(str3, str1);
t1.start(); t2.start(); t3.start(); }}
public class Sample09 { /** * @param args */ public static void main(String[] args) { // ExecutorService es = Executors.newFixedThreadPool(3); // ExecutorService es = Executors.newSingleThreadExecutor(); ExecutorService es = Executors.newCachedThreadPool(); for (int i = 0; i < 1000; i++) { Task t = new Task(); es.submit(t); }
System.out.println("加载任务完成"); es.shutdown(); System.out.println("main is over"); } }class Task implements Runnable { private String name = ""; private static int num = 1;
private static int step = 0; private long sleepTime = 200; public Task(String name, long sleepTime) { this.name = name; this.sleepTime = sleepTime; } public Task() { this("task-" + num, 200); num++; } public void run() { int num = 1; int all = new Random().nextInt(20) + 1; System.out.println("\n==========" + Thread.currentThread().getName() + "开始执行" + name + "任务(该任务有" + all + "步)" + "=========="); step = 0; while (num <= all) { System.out.print("执行任务" + name + "第" + num++ + "步 "); step++; if (step % 6 == 0) { System.out.println(); } try { Thread.sleep(sleepTime); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("\n==========" + Thread.currentThread().getName() + "执行完毕=========="); step = 0; } }
class ProduceInteger extends Thread { private HoldInteger sharedObject; public ProduceInteger(HoldInteger shared) { sharedObject=shared; } public void run() { for(int count=1;count <8;count ) { try { Thread.sleep(((int)Math.random()*3000)); sharedObject.setSharedInt(count); } catch(InterruptedException exception) { } System.out.println( "Producer # " count "done producing, put: " count); } } } class ConsumeInteger extends Thread { private HoldInteger sharedObject; public ConsumeInteger(HoldInteger shared) { sharedObject=shared; } public void run() { int value=0; for(int i=1;i <8;i ) { try { Thread.sleep(((int)Math.random()*3000)); value=sharedObject.getSharedInt(); } catch(InterruptedException exception) { } System.out.println( "Consumer # " i "done consuming, got: " value); } } } class HoldInteger { private int sharedInt=-1; boolean available=false; public synchronized void setSharedInt(int value) { while(available==true) { try { System.out.println( "Producer tries to wite,Buffer is full.Wait "); wait(); } catch(InterruptedException e) { } } sharedInt=value; available=true; notifyAll(); } public synchronized int getSharedInt() { while(available==false) { try { System.out.println( "Consumer tries to read,Buffer is empty.Wait "); wait(); } catch(InterruptedException e) { } } available=false; notifyAll(); System.out.println( "实验 "); return sharedInt; } } public class ProdAndCons { public static void main(String[] args) { HoldInteger sharedObject=new HoldInteger(); ProduceInteger producer=new ProduceInteger(sharedObject); ConsumeInteger consumer=new ConsumeInteger(sharedObject); producer.start(); consumer.start(); } }
public class Sample07 { /**
* @param args
*/
public static void main(String[] args) {
Warehouse wh = new Warehouse();
Product p1 = new Product(wh);
Product p2 = new Product(wh);
Consumer c = new Consumer(wh); c.start(); try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
} p1.start();
p2.start();
}}class Product extends Thread {
private Warehouse wh = null; public Product(Warehouse wh) {
this.wh = wh;
} public void run() {
int num = 1; while (num < 21) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
wh.push(num++);
}
}
}class Consumer extends Thread {
private Warehouse wh = null; public Consumer(Warehouse wh) {
this.wh = wh;
} public void run() {
while (true) { try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (wh.pop() == 20) {
break;
}
}
}
}class Warehouse {
private int num = 0; private boolean isFull = false; public synchronized void push(int num) {
if (!isFull) {
this.num = num;
System.out.println("生产者" + Thread.currentThread().getName() + "放入--->" + num);
isFull = true;
notify();
} if (isFull) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} public synchronized int pop() {
if (isFull) {
System.out.println("消费者获得--->" + num);
isFull = false;
notifyAll();
return num;
} if (!isFull) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return -1;
}
}
public class Sample08 extends Thread {
private Object o1 = null;
private Object o2 = null;
public Sample08(Object o1, Object o2) {
this.o1 = o1;
this.o2 = o2;
}
public void run() {
synchronized (o1) {
System.out.println(Thread.currentThread().getName() + "锁住对象" + o1);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (o2) {
System.out.println(Thread.currentThread().getName() + "锁住对象" + o2);
}
System.out.println(Thread.currentThread().getName() + "释放对象" + o2);
}
System.out.println(Thread.currentThread().getName() + "释放对象" + o1);
} /**
* @param args
*/
public static void main(String[] args) {
String str1 = "str1";
String str2 = "str2";
String str3 = "str3";
Sample08 t1 = new Sample08(str1, str2);
Sample08 t2 = new Sample08(str2, str3);
Sample08 t3 = new Sample08(str3, str1);
t1.start();
t2.start();
t3.start();
}}
public class Sample09 { /**
* @param args
*/
public static void main(String[] args) {
// ExecutorService es = Executors.newFixedThreadPool(3);
// ExecutorService es = Executors.newSingleThreadExecutor();
ExecutorService es = Executors.newCachedThreadPool(); for (int i = 0; i < 1000; i++) {
Task t = new Task();
es.submit(t);
}
System.out.println("加载任务完成");
es.shutdown();
System.out.println("main is over");
}
}class Task implements Runnable {
private String name = ""; private static int num = 1;
private static int step = 0; private long sleepTime = 200; public Task(String name, long sleepTime) {
this.name = name;
this.sleepTime = sleepTime;
} public Task() {
this("task-" + num, 200);
num++;
} public void run() {
int num = 1;
int all = new Random().nextInt(20) + 1;
System.out.println("\n==========" + Thread.currentThread().getName()
+ "开始执行" + name + "任务(该任务有" + all + "步)" + "==========");
step = 0;
while (num <= all) {
System.out.print("执行任务" + name + "第" + num++ + "步 ");
step++;
if (step % 6 == 0) {
System.out.println();
}
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("\n==========" + Thread.currentThread().getName()
+ "执行完毕==========");
step = 0;
}
}
{
private HoldInteger sharedObject;
public ProduceInteger(HoldInteger shared)
{
sharedObject=shared;
} public void run()
{
for(int count=1;count <8;count )
{
try
{
Thread.sleep(((int)Math.random()*3000));
sharedObject.setSharedInt(count);
}
catch(InterruptedException exception)
{
}
System.out.println( "Producer # " count "done producing, put: " count);
}
}
} class ConsumeInteger extends Thread
{
private HoldInteger sharedObject;
public ConsumeInteger(HoldInteger shared)
{
sharedObject=shared;
} public void run()
{
int value=0;
for(int i=1;i <8;i )
{
try
{
Thread.sleep(((int)Math.random()*3000));
value=sharedObject.getSharedInt();
}
catch(InterruptedException exception)
{
}
System.out.println( "Consumer # " i "done consuming, got: " value);
}
} } class HoldInteger
{
private int sharedInt=-1;
boolean available=false; public synchronized void setSharedInt(int value)
{
while(available==true)
{
try
{
System.out.println( "Producer tries to wite,Buffer is full.Wait ");
wait();
}
catch(InterruptedException e)
{
}
}
sharedInt=value;
available=true;
notifyAll();
}
public synchronized int getSharedInt()
{
while(available==false)
{
try
{
System.out.println( "Consumer tries to read,Buffer is empty.Wait ");
wait();
}
catch(InterruptedException e)
{
}
}
available=false;
notifyAll();
System.out.println( "实验 ");
return sharedInt;
}
} public class ProdAndCons { public static void main(String[] args) {
HoldInteger sharedObject=new HoldInteger();
ProduceInteger producer=new ProduceInteger(sharedObject);
ConsumeInteger consumer=new ConsumeInteger(sharedObject);
producer.start();
consumer.start(); } }
中国网管联盟bitsCN.com
代码如下: import java.util.Random;
public class DiningPhils
{
public static void main(String[] args)
{
int n = 10;
if( n < 1)
{
System.err.println( "DiningPils <# of philosophers>" );
System.exit(-1);
}
DiningPhils self = new DiningPhils();
self.init(n);
}
public int getCount()
{
return n;
}
public void setChopstick( int i, boolean v)
{
chops[ i ] = v;
}
public boolean getChopstick( int i )
{
return chops[i];
}
private void init( final int N)
{
r = new Random();
n = ( N < 0 || N > maxPhils ) ? maxPhils : N;
chops = new boolean[n];
phils = new Philosopher[n];
initPhils();
dumpStatus();
}
private void initPhils()
{
for( int i = 0; i< n; i++ )
{
phils[i] = new Philosopher( this, i );
phils[i].setTimeSlice( generateTimeSlice());
phils[i].setPriority( Thread.NORM_PRIORITY - 1);
/**哲学家进程降低一级,使所有哲学家进程
*全部初始化完毕前不会有哲学家进程抢占主线程*/
}
while( moreToStart() )
{
int i = Math.abs( r.nextInt()) % n;
if( !phils[i].isAlive())
{
System.out.println( " ### Philosopher " +
String.valueOf( i ) + " started.");
phils[i].start();
}
}
System.out.println( "\nPhilosophers Chopsticks"
+ "\n(1 = eating, 0 = thinking) (1 = taken, 0 = free)");
}
public int generateTimeSlice()
{
int ts = Math.abs(r.nextInt()) % (maxEat + 1);
if( ts == 0 )
ts = minEat;
return ts;
}
public void dumpStatus()
{
for( int i = 0; i < n; i++)
System.out.print(phils[i].getEat() ? 1 : 0);
for( int i = n; i < maxPhils + 4; i++ )
System.out.print(" ");
for( int i = 0; i < n; i++)
System.out.print(chops[i]? 1:0);
System.out.println();
}
private boolean moreToStart()
{
for( int i = 0; i < phils.length; i++ )
{
if( !phils[i].isAlive())
return true;
}
return false;
}
private int n;
private Philosopher[] phils;
private boolean[] chops;
private Random r;
private static final int maxPhils = 24; //最多哲学家数
private static final int maxEat = 4; //最多进餐时间
private static final int minEat = 1; //最少进餐时间
}
class Philosopher extends Thread
{
public Philosopher( DiningPhils HOST , int i )
{
host = HOST;
index = i;
}
public void setTimeSlice( int TS )
{
ts = TS;
}
public void setLeftChopstick( boolean flag )
{
host.setChopstick(index, flag);
}
public void setRightChopstick( boolean flag )
{
host.setChopstick((index + 1)% host.getCount() , flag);
}
private void releaseChopsticks()
{
setLeftChopstick(false);
setRightChopstick(false);
}
public boolean chopsticksFree()
{
return !host.getChopstick(index) &&
!host.getChopstick((index+1)%host.getCount());
}
public void run()
{
while(true)
{
grabChopsticks();
eat();
think();
}
}
private synchronized void grabChopsticks() /**临界区函数,确保哲学家在没有筷子或筷子不够时思考,满足条件后才就餐*/
{
while( !chopsticksFree())
{
try
{
wait();
}
catch( InterruptedException e){}
}
takeChopsticks();
notifyAll();
}
private void takeChopsticks()
{
setLeftChopstick( true );
setRightChopstick( true );
setEat(true);
host.dumpStatus();
}
private void eat()
{
pause();
setEat( false );
releaseChopsticks();
}
private void think()
{
pause();
}
private void pause()
{
setTimeSlice( host.generateTimeSlice());
try
{
sleep(ts*1000);
}
catch( InterruptedException e){}
}
private void setEat(boolean v)
{
isEating = v;
}
public boolean getEat()
{
return isEating;
}
private DiningPhils host;
private boolean isEating;
private int index;
private int ts;
}
...{
Queue<_Info> _queue;
Event_Trigger _produce;
Event_Trigger _consume;
Unique _locker = new Unique();
public Info_Queue(int size)
...{
this._queue = new Queue<_Info>(size);
this._produce = new Event_Trigger(size);
this._consume = new Event_Trigger();
}
public void Push(_Info item)
...{
this._produce.Wait();
this._locker.Lock();
this._queue.Enqueue(item);
this._locker.UnLock();
this._consume.Post();
}
public _Info Pop()
...{
this._consume.Wait();
_Info item = default(_Info);
this._locker.Lock();
item = this._queue.Dequeue();
this._locker.UnLock();
this._produce.Post();
return item;
}
public int Count()
...{
return this._queue.Count;
}
public void Clear()
...{
this._queue.Clear();
this._locker.Close();
this._produce.Close();
this._consume.Close();
}
}