aboutsummaryrefslogtreecommitdiff
path: root/CS2452/assign5/src/ResourceReader.java
blob: f9f0f712c8a0e6e1f6da6d26360472e2ba243aee (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import java.io.*;
import java.util.concurrent.Semaphore;

public class ResourceReader implements Runnable
{
	public static double cor = 0;
	public static Semaphore flg1 = new Semaphore(1);

	Thread t;
	byte[] res = null, sentinel = null;
	DataOutputStream dout = null;
	Semaphore flg = null;
	Semaphore flg2 = null;

	ResourceReader(DataOutputStream dot, byte[] r, Semaphore s, Semaphore s2)
	{
		res = r;
		dout = dot;
		flg = s;
		flg2 = s2;
		sentinel = new byte[32768];
		for (int i = 0; i < sentinel.length; i++ )
			sentinel[i] = 65;
		t = new Thread(this, "ResourceReader");
		t.start();
	}

	public void run()
	{
		int i;
		byte value = 33;
		boolean running = true;

		System.out.println("ResourceReader: starts");
		while (running)
		{
			try
			{

				flg2.acquire();
				flg2.release();
				flg1.acquire();
				if (cor == 0)
				{
					flg.acquire();
					cor++ ;
					flg1.release();
					for (int j = 0; j < 50; j++ )
						dout.write(res, 0, res.length);
					dout.write(sentinel, 0, sentinel.length);
					flg.release();
				}
				else
				{
					cor++ ;
					flg1.release();
					for (int j = 0; j < 50; j++ )
						dout.write(res, 0, res.length);
					dout.write(sentinel, 0, sentinel.length);
				}
				flg1.acquire();
				cor-- ;
				flg1.release();

				System.out.println("ResourceReader: sent a bunch");
				Thread.sleep(100);
				running = false;
			} catch (Exception e)
			{
				e.printStackTrace();
				try
				{
					dout.close();
				} catch (Exception e2)
				{
				}
				return;
			}
		}
		System.out.println("ResourceReader: ends");
		try
		{
			dout.close();
		} catch (Exception e2)
		{
		}

	}
}