Separating into Tech and SysDev

This commit is contained in:
2022-05-07 23:24:08 +02:00
parent ae93dfdacb
commit e49df859aa
88 changed files with 0 additions and 0 deletions

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="output" path="bin"/>
</classpath>

View File

@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>CircularBuffer</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

View File

@@ -0,0 +1,48 @@
// All non primary objects (int, char etc) have wait, notify, notifyAll
// Methods "synchronized" to provide intrinsic locks
// If a thread calling wait() method does not own the inherent lock,
// an error will be thrown.
public class Buffer {
private int BufferSize = 4;
private int[] Container = new int[BufferSize];
private int PosR=0, PosW=0;
public synchronized int Read() {
while (true) {
if ( PosR == PosW ) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
int v=Container[ PosR ];
PosR = (PosR+1) % BufferSize;
System.out.println("Read pos " + PosR);
notifyAll();
return v;
}
}
}
public synchronized void Write( int Val ) {
while (true) {
if (((PosW + 1) % BufferSize) == PosR) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
Container[PosW] = Val;
PosW = (PosW+1) % BufferSize;
System.out.println("Write pos " + PosW);
notifyAll();
return;
}
}
}
}

View File

@@ -0,0 +1,25 @@
public class CircularBuffer {
static Buffer MyBuffer = new Buffer();
public static void main(String[] args) {
// TODO Auto-generated method stub
new Thread(() -> {
System.out.println("Producer running");
for ( int nn=0; nn < 20; nn++) {
MyBuffer.Write( nn );
System.out.println("Producer Wrote " + nn);
}
}).start();
new Thread(() -> {
System.out.println("Consumer running");
for ( int nn=0; nn < 20; nn++ ) {
System.out.println("Consumer Read " + MyBuffer.Read());
}
}).start();
}
}

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="output" path="bin"/>
</classpath>

View File

@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>ClassicIoBuffered</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,54 @@
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
*
*/
/**
* @author KAJE
*
*/
public class ClassicIoBuffered {
private static int lineCount(String path, boolean doDance){
if ( ! doDance ) return -1;
FileInputStream fis = null;
try {
fis = new FileInputStream(path);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedInputStream bis = new BufferedInputStream(fis);
int cnt = 0;
int b;
try {
while ((b = bis.read()) != -1) {
if (b == '\n') cnt++;
}
bis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return cnt;
}
/**
* @param args
*/
public static void main(String[] args){
long startTime = System.nanoTime();
lineCount("", false);
long dryRun = System.nanoTime() - startTime;
startTime = System.nanoTime();
int lines = lineCount("input.txt", true);
long stopTime = System.nanoTime();
System.out.println("Lines: " + String.valueOf(lines));
System.out.println("Time it took: " + (stopTime - startTime - dryRun) + " ");
}
}

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="output" path="bin"/>
</classpath>

View File

@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>ClassicIoManBuffered</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,49 @@
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* @author KAJE
*
*/
public class ClassicIoManBuffered {
private static int lineCount(String path, boolean doDance){
if ( ! doDance ) return -1;
FileInputStream fis = null;
try {
fis = new FileInputStream( path );
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte buf[] = new byte[2048];
int cnt = 0;
int n;
try {
while ((n = fis.read(buf)) != -1) {
for (int i = 0; i < n; i++) {
if (buf[i] == '\n') cnt++;
}
}
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return cnt;
}
public static void main(String[] args){
long startTime = System.nanoTime();
lineCount("", false);
long dryRun = System.nanoTime() - startTime;
startTime = System.nanoTime();
int lines = lineCount("input.txt", true);
long stopTime = System.nanoTime();
System.out.println("Lines: " + String.valueOf(lines));
System.out.println("Time it took: " + (stopTime - startTime - dryRun) + " ");
}
}

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="output" path="bin"/>
</classpath>

View File

@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>ClassicIoUnbuffered</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,46 @@
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* @author KAJE
*
*/
public class ClassicIoUnbuffered {
private static int lineCount(String path, boolean doDance){
if ( ! doDance ) return -1;
FileInputStream fis = null;
try {
fis = new FileInputStream(path);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return -1;
}
int cnt = 0;
int b;
try {
while ((b = fis.read()) != -1) {
if (b == '\n') cnt++;
}
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return cnt;
}
public static void main(String[] args){
long startTime = System.nanoTime();
lineCount("", false);
long dryRun = System.nanoTime() - startTime;
startTime = System.nanoTime();
int lines = lineCount("input.txt", true);
long stopTime = System.nanoTime();
System.out.println("Lines: " + String.valueOf(lines));
System.out.println("Time it took: " + (stopTime - startTime - dryRun) + " " + dryRun);
}
}

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="output" path="bin"/>
</classpath>

View File

@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>ClassicIoWholeFile</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,52 @@
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
*
*/
/**
* @author KAJE
*
*/
public class ClassicIoWholeFile {
private static int lineCount(String path, boolean doDance){
if ( ! doDance ) return -1;
int len = (int)(new File(path).length());
int cnt = 0;
FileInputStream fis;
try {
fis = new FileInputStream( path );
byte buf[] = new byte[len];
try {
fis.read(buf);
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0; i < len; i++) {
if (buf[i] == '\n') cnt++;
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return cnt;
}
public static void main(String[] args){
long startTime = System.nanoTime();
lineCount("", false);
long dryRun = System.nanoTime() - startTime;
startTime = System.nanoTime();
int lines = lineCount("input.txt", true);
long stopTime = System.nanoTime();
System.out.println("Lines: " + String.valueOf(lines));
System.out.println("Time it took: " + (stopTime - startTime - dryRun) + " ");
}
}

View File

@@ -0,0 +1,103 @@
-- This Script is part of the AnomalyBank Series
--
-- Problem: Inconsistent retrieval
--
-- Revision History
-- 2019.04.09 Karsten Jeppesen (kaje@ucn.dk) initial push
-- 2020.03.30 Karsten Jeppesen (kaje@ucn.dk) Spellcheck
--
-- Anomaly: Inconsistent retrieval
--
-- PreReq: SQL - AnomalyBank - 01 - Initialize Bank
--
-- Distributed Systems, Concepts and Design, page 684, Figure 16.6
-- The Inconsistent Retrievals Problem, Transaction W
-- Start this script no later than 5 secs after Transaction V
-- +------------------------------+------------------------------------+
-- | Transaction V | Transaction W |
-- +------------------------------+------------------------------------+
-- | a.withdraw(100); 100 | |
-- | | total = a.getBalance( ) 100 |
-- | | total = total + b.getBalance() 300 |
-- | | total = total + c.getBalance() 500 |
-- | b.deposit(100) 200 | |
-- +------------------------------+------------------------------------+
--
-- The Correct Branch balance is 600 NOT 500
--
-- EXERCISE: Try the different ISOLATION levels.
-- SET TRANSACTION ISOLATION LEVEL
-- { READ UNCOMMITTED
-- | READ COMMITTED
-- | REPEATABLE READ
-- | SNAPSHOT
-- | SERIALIZABLE
-- }
USE AnomalyBank
-- CHOOSE ONE OF THE FOLLOWING BY UNCOMMENTING
--SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
--SET TRANSACTION ISOLATION LEVEL READ COMMITTED
--SET TRANSACTION ISOLATION LEVEL REPEATABLE READ
--SET TRANSACTION ISOLATION LEVEL SNAPSHOT
--SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
-- Nothing to initialize
-- And here comes The Inconsistent Retrievals Problem
DECLARE @Balance int
DECLARE @Total int
DECLARE @Done int = 0;
DECLARE @DeadlockErr int = 1205;
DECLARE @LockTimeout int = 1222;
WHILE @Done = 0
BEGIN
PRINT 'Branch totalling start';
BEGIN TRANSACTION T1 WITH MARK N'Branch Total';
BEGIN TRY
SET @Total = 0;
-- total = a.getBalance( )
SELECT @Balance=Balance FROM Accounts WHERE Customer='a';
SET @Total = @Total + @Balance;
-- total = total + b.getBalance()
SELECT @Balance=Balance FROM Accounts WHERE Customer='b';
SET @Total = @Total + @Balance;
-- total = total + c.getBalance()
SELECT @Balance=Balance FROM Accounts WHERE Customer='c';
SET @Total = @Total + @Balance;
PRINT N'Total balance is';
PRINT @Total;
SET @Done = 1;
COMMIT TRANSACTION T1;
END TRY
BEGIN CATCH
if (ERROR_NUMBER() = @DeadlockErr)
BEGIN
PRINT 'ABORTED BY DEADLOCK';
ROLLBACK;
CONTINUE;
END
if (ERROR_NUMBER() = @LockTimeout)
BEGIN
PRINT 'ABORTED BY LOCK TIMEOUT';
ROLLBACK;
CONTINUE;
END
SELECT 'ABORTED BY UNHANDLED ERROR';
SET @Done = 1;
END CATCH
END
select * FROM Accounts
USE master

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="output" path="bin"/>
</classpath>

View File

@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>ConditionDemo</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

View File

@@ -0,0 +1,57 @@
The conviction of 109 killers, 81 rapists and a man found guilty of both crimes in UK courts was not passed on to the criminals<6C> home EU countries due to a massive computer failure and subsequent cover-up, the Guardian can reveal.
The most serious cases are among a total of 112,490 criminal convictions not sent to the relevant EU capitals over an eight-year period due to a catastrophic computer error, which some fear has put lives at risk.
The scandal largely involves dual nationals, who are only rarely deported even after lengthy prison sentences, leaving EU member states potentially blind as to whether those convicted of crimes in the UK have since entered their country.
The revelation will be highly embarrassing at a time when UK police forces are often relying on goodwill for continued cooperation on the sharing of information after the loss of access to EU databases due to Brexit.
The Guardian can reveal:
The failure to comply with EU law and notify member states was first discovered within Whitehall at least six years ago, and a provisional plan to update them had been drawn up at that time by the Criminal Records Office. It was not acted upon amid concerns about the <20>reputational impact<63> on Britain.
The lack of notification included 191 individuals who were convicted of either aggravated intentional killing, aggravated rape, intentional killing, rape of a minor, unintentional killing, aggravated cases of intentional killing and intentional killing. Of those, 109 were convicted killers, 81 were rapists, and <20>one subject was convicted of both types of offences<65>.
EU member states were only alerted to the problem last autumn after this newspaper published incriminating minutes of a meeting at the Criminal Records Office. <20>You may be aware through UK media coverage earlier this year of a number of notifications not sent to EU member states since [European criminal records information system] was implemented in April 2012,<2C> read the letter to member states from the criminal records office. <20>This is clearly a significant number that will have an impact upon you.<2E>
Of the total of 112,490 convictions in the UK courts that had not been passed on to the EU member states, documents show that by the 15 February notification had belatedly been made of 81,706 cases, including 19,565 to Poland, 17,996 to Ireland and 12,466 to Romania, according to an FOI response. The UK criminal records office said a further 7,100 notifications had been made in the last two weeks.
The failure relates mainly to dual EU nationals and individuals where a fingerprint is missing from the records. But a series of other errors in the system have led to a failure to notify. Poland was not told of convictions of 15 of its nationals as they had been erroneously submitted to the police national computer as being from the Pitcairn Islands.
Officials noted in 2015 that the system was prone to errors, with several convicted criminals recorded as coming from a tiny atoll in the Pacific Ocean known as Wake Island when in reality they lived in Wakefield, West Yorkshire.
The problem was caused by the police national computer, a database used by law enforcement organisations across the UK operated by the Home Office, which generates daily files of the latest updates on convictions.
If a foreign offender is sentenced, then Acro Criminal Records Office, a UK body responsible for international police data sharing, is legally obliged under EU law to alert police in convicted criminals<6C> home country.
Six years ago, officials realised there was a serious problem in the system and warned the Home Office, documents obtained under the Freedom of Information Act by the Guardian revealed on Tuesday.
A note written on 10 February 2015 for Acro<72>s strategic meeting explained that many of these daily activity files (DAFs) were not being created as had been intended.
When no fingerprints were recorded or when the offender had dual nationality, the file was not being generated and so <20>in the region of 30% of DAF<41> were being <20>suppressed<65>.
In addition, the files were not created when an offender was recorded as coming from 49 small current countries and another 92 historic ones,
such as Rhodesia.
The report makes it plain that the issue had been raised at a senior level within the Home Office by the most senior figures in the UK Criminal Records Office, saying: <20>Significant funds and resources would be needed to process the missing records and engagement has already started with HO colleagues, by the head of Acro.<2E>
A second internal Acro report reveals that a detailed <20>change request<73> to correct the DAF software was sent to the Home Office in January 2017 but that it was delayed.
Police continued to raise the issue with government but it was kept from European law enforcement agencies despite the legal obligation upon them. A note from an Acro meeting in May 2019 reported: <20>There is a nervousness from Home Office around sending the historical notifications out dating back to 2012 due to the reputational impact this could have.<2E>
It was only after the scandal of the missing alerts was uncovered by the Guardian a year ago that ministers informed parliament and committed to fix it. At the time the number of missed records was estimated at 75,000.
Sophie in <20>t Veld, a Dutch MEP who sits on the European parliament<6E>s civil liberties, justice and home affairs committee, said: <20>The day will come that one of these people commits a very serious crime and then everybody is going to be up in arms and say: how come we didn<64>t know about it?<3F>
In <20>t Veld said the scandal raised questions over whether or not the UK would abide by the security and data-sharing arrangements agreed in the Brexit deal.
<EFBFBD>I<EFBFBD>m worried, and irritated. What<61>s the point in having an agreement if even before the ink is dry, they<65>re not living up to it,<2C> she said. <20>Already the UK was not meeting its obligations when it was a member of the EU and now we have less means to enforce it.<2E>
Lord Kennedy of Southwark, a shadow Home Office minister, said: <20>I am appalled at what has been revealed here with catastrophic failures by the Home Office to notify other European countries of people convicted of the most serious of offences including killers and rapists.
<EFBFBD>The damage caused to the reputation of British policing by this failure and cover-up by the Home Office cannot be overstated.<2E>
A UK government spokesperson said: <20>The Home Office has been working with Acro at pace to ensure the necessary data is shared with affected member states.
<EFBFBD>The majority have now been issued and we are working through the remaining data files, which require careful manual intervention. The individuals relating to the data have all faced justice in the UK and will have received the appropriate sentence.<2E>

View File

@@ -0,0 +1,22 @@
// Running the world
//
public class ConditionDemo {
public static void main(String[] args) throws InterruptedException {
SharedFiFoQueue sharedQueue = new SharedFiFoQueue(10);
//Create a producer and a consumer.
Thread producer = new Producer(sharedQueue);
Thread consumer = new Consumer(sharedQueue);
//Start both threads.
producer.start();
consumer.start();
//Wait for both threads to terminate.
producer.join();
consumer.join();
}
}

View File

@@ -0,0 +1,42 @@
// Consuming the words from the queue.
// Counting total number of words and keeping track of unique words
//
import java.util.HashSet;
import java.util.Set;
public class Consumer extends Thread {
private Set knownObjects = new HashSet();
private int total = 0;
private int unique = 0;
private SharedFiFoQueue queue;
public Consumer(SharedFiFoQueue queue) {
this.queue = queue;
}
@Override
public void run() {
try {
do {
Object obj = queue.remove();
if(obj == null)
break;
total++;
if(!knownObjects.contains(obj)) {
unique++;
knownObjects.add(obj);
}
System.out.println("[Consumer] Read the element: " + obj.toString());
} while(true);
}
catch (InterruptedException ex) {
System.err.println("An InterruptedException was caught: " + ex.getMessage());
ex.printStackTrace();
}
System.out.println("\n[Consumer] " + total + " words read counting " + unique + " unique words");
}
}

View File

@@ -0,0 +1,57 @@
// The file "input.txt" is read on a line basis.
// Words are separated and fed to the queue
// Finally a null object is fed to the queue to signal the consumer the end of operation
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Producer extends Thread {
private static String FILENAME = "input.txt";
private SharedFiFoQueue queue;
public Producer(SharedFiFoQueue queue) {
this.queue = queue;
}
@Override
public void run() {
BufferedReader rd = null;
try {
rd = new BufferedReader(new FileReader(FILENAME));
String inputLine = null;
while((inputLine = rd.readLine()) != null) {
String[] inputWords = inputLine.split(" ");
for(String inputWord: inputWords) {
queue.add(inputWord);
System.out.println("[Producer] Wrote the element: " + inputWord);
}
}
// End of the world
queue.add(null);
}
catch (InterruptedException ex) {
System.err.println("An InterruptedException was caught: " + ex.getMessage());
ex.printStackTrace();
}
catch (IOException ex) {
System.err.println("An IOException was caught: " + ex.getMessage());
ex.printStackTrace();
}
finally {
try {
if(rd != null)
rd.close();
}
catch (IOException ex) {
System.err.println("An IOException was caught: " + ex.getMessage());
ex.printStackTrace();
}
}
}
}

View File

@@ -0,0 +1,57 @@
// Similar to the Circular buffer example, but with objects
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class SharedFiFoQueue {
private Object[] elems = null;
private int PosW = 0;
private int PosR = 0;
private Lock lock = new ReentrantLock();
private Condition isEmpty = lock.newCondition();
private Condition isFull = lock.newCondition();
public SharedFiFoQueue(int capacity) {
this.elems = new Object[capacity];
}
public void add(Object elem) throws InterruptedException {
lock.lock();
while( ((PosW + 1) % elems.length) == PosR)
isFull.await();
elems[PosW] = elem;
//We need the modulo, in order to avoid going out of bounds.
PosW = (PosW + 1) % elems.length;
//Notify the consumer that there is data available.
isEmpty.signal();
lock.unlock();
}
public Object remove() throws InterruptedException {
Object elem = null;
lock.lock();
while( PosR == PosW )
isEmpty.await();
elem = elems[PosR];
//We need the modulo, in order to avoid going out of bounds.
PosR = (PosR + 1) % elems.length;
//Notify the producer that there is space available.
isFull.signal();
lock.unlock();
return elem;
}
}

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="output" path="bin"/>
</classpath>

View File

@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>Game-1</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

Binary file not shown.

After

Width:  |  Height:  |  Size: 738 B

View File

@@ -0,0 +1,84 @@
// Origin: https://zetcode.com/javagames/movingsprites/
package Game;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.Timer;
import javax.swing.JPanel;
public class Board extends JPanel implements ActionListener {
private Timer timer;
private SpaceShip spaceShip;
private final int DELAY = 10;
public Board() {
initBoard();
}
private void initBoard() {
addKeyListener(new TAdapter());
setBackground(Color.black);
setFocusable(true);
spaceShip = new SpaceShip();
timer = new Timer(DELAY, this);
timer.start();
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
doDrawing(g);
Toolkit.getDefaultToolkit().sync();
}
private void doDrawing(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(spaceShip.getImage(), spaceShip.getX(),
spaceShip.getY(), this);
}
@Override
public void actionPerformed(ActionEvent e) {
step();
}
private void step() {
spaceShip.move();
repaint(spaceShip.getX()-1, spaceShip.getY()-1,
spaceShip.getWidth()+2, spaceShip.getHeight()+2);
}
private class TAdapter extends KeyAdapter {
@Override
public void keyReleased(KeyEvent e) {
spaceShip.keyReleased(e);
}
@Override
public void keyPressed(KeyEvent e) {
spaceShip.keyPressed(e);
}
}
}

View File

@@ -0,0 +1,106 @@
// Origin: https://zetcode.com/javagames/movingsprites/
package Game;
import java.awt.Image;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
public class SpaceShip {
private int dx;
private int dy;
private int x = 40;
private int y = 60;
private int w;
private int h;
private Image image;
public SpaceShip() {
loadImage();
}
private void loadImage() {
ImageIcon ii = new ImageIcon("src/resources/spaceship.png");
image = ii.getImage();
w = image.getWidth(null);
h = image.getHeight(null);
}
public void move() {
x += dx;
y += dy;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getWidth() {
return w;
}
public int getHeight() {
return h;
}
public Image getImage() {
return image;
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT) {
dx = -2;
}
if (key == KeyEvent.VK_RIGHT) {
dx = 2;
}
if (key == KeyEvent.VK_UP) {
dy = -2;
}
if (key == KeyEvent.VK_DOWN) {
dy = 2;
}
}
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT) {
dx = 0;
}
if (key == KeyEvent.VK_RIGHT) {
dx = 0;
}
if (key == KeyEvent.VK_UP) {
dy = 0;
}
if (key == KeyEvent.VK_DOWN) {
dy = 0;
}
}
}

View File

@@ -0,0 +1,35 @@
// Origin: https://zetcode.com/javagames/movingsprites/
package Game;
import java.awt.EventQueue;
import javax.swing.JFrame;
public class TheGame extends JFrame {
public TheGame() {
initUI();
}
private void initUI() {
add(new Board());
setTitle("Moving sprite");
setSize(800, 800);
setLocationRelativeTo(null);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
TheGame ex = new TheGame();
ex.setVisible(true);
});
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 738 B

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="output" path="bin"/>
</classpath>

View File

@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>Game-2</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

View File

@@ -0,0 +1,112 @@
package Game;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.List;
import javax.swing.Timer;
import javax.swing.JPanel;
public class Board extends JPanel implements ActionListener {
private final int ICRAFT_X = 40;
private final int ICRAFT_Y = 60;
private final int DELAY = 10;
private Timer timer;
private SpaceShip spaceShip;
public Board() {
initBoard();
}
private void initBoard() {
addKeyListener(new TAdapter());
setBackground(Color.BLACK);
setFocusable(true);
spaceShip = new SpaceShip(ICRAFT_X, ICRAFT_Y);
timer = new Timer(DELAY, this);
timer.start();
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
doDrawing(g);
Toolkit.getDefaultToolkit().sync();
}
private void doDrawing(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(spaceShip.getImage(), spaceShip.getX(),
spaceShip.getY(), this);
List<Missile> missiles = spaceShip.getMissiles();
for (Missile missile : missiles) {
g2d.drawImage(missile.getImage(), missile.getX(),
missile.getY(), this);
}
}
@Override
public void actionPerformed(ActionEvent e) {
updateMissiles();
updateSpaceShip();
repaint();
}
private void updateMissiles() {
List<Missile> missiles = spaceShip.getMissiles();
for (int i = 0; i < missiles.size(); i++) {
Missile missile = missiles.get(i);
if (missile.isVisible()) {
missile.move();
} else {
missiles.remove(i);
}
}
}
private void updateSpaceShip() {
spaceShip.move();
}
private class TAdapter extends KeyAdapter {
@Override
public void keyReleased(KeyEvent e) {
spaceShip.keyReleased(e);
}
@Override
public void keyPressed(KeyEvent e) {
spaceShip.keyPressed(e);
}
}
}

View File

@@ -0,0 +1,30 @@
// Origin: https://zetcode.com/javagames/movingsprites/
package Game;
public class Missile extends Sprite {
private final int BOARD_WIDTH = 800;
private final int MISSILE_SPEED = 2;
public Missile(int x, int y) {
super(x, y);
initMissile();
}
private void initMissile() {
loadImage("src/resources/missile.png");
getImageDimensions();
}
public void move() {
x += MISSILE_SPEED;
if (x > BOARD_WIDTH) {
visible = false;
}
}
}

View File

@@ -0,0 +1,87 @@
// Origin: https://zetcode.com/javagames/movingsprites/
package Game;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;
public class SpaceShip extends Sprite {
private int dx;
private int dy;
private List<Missile> missiles;
public SpaceShip(int x, int y) {
super(x, y);
initSpaceShip();
}
private void initSpaceShip() {
missiles = new ArrayList<>();
loadImage("src/resources/spaceship.png");
getImageDimensions();
}
public void move() {
x += dx;
y += dy;
}
public List<Missile> getMissiles() {
return missiles;
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_SPACE) {
fire();
}
if (key == KeyEvent.VK_LEFT) {
dx = -1;
}
if (key == KeyEvent.VK_RIGHT) {
dx = 1;
}
if (key == KeyEvent.VK_UP) {
dy = -1;
}
if (key == KeyEvent.VK_DOWN) {
dy = 1;
}
}
public void fire() {
missiles.add(new Missile(x + width, y + height / 2));
}
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT) {
dx = 0;
}
if (key == KeyEvent.VK_RIGHT) {
dx = 0;
}
if (key == KeyEvent.VK_UP) {
dy = 0;
}
if (key == KeyEvent.VK_DOWN) {
dy = 0;
}
}
}

View File

@@ -0,0 +1,56 @@
// Origin: https://zetcode.com/javagames/movingsprites/
package Game;
import java.awt.Image;
import javax.swing.ImageIcon;
public class Sprite {
protected int x;
protected int y;
protected int width;
protected int height;
protected boolean visible;
protected Image image;
public Sprite(int x, int y) {
this.x = x;
this.y = y;
visible = true;
}
protected void loadImage(String imageName) {
ImageIcon ii = new ImageIcon(imageName);
image = ii.getImage();
}
protected void getImageDimensions() {
width = image.getWidth(null);
height = image.getHeight(null);
}
public Image getImage() {
return image;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public boolean isVisible() {
return visible;
}
public void setVisible(Boolean visible) {
this.visible = visible;
}
}

View File

@@ -0,0 +1,35 @@
// Origin: https://zetcode.com/javagames/movingsprites/
package Game;
import java.awt.EventQueue;
import javax.swing.JFrame;
public class TheGame extends JFrame {
public TheGame() {
initUI();
}
private void initUI() {
add(new Board());
setTitle("Moving sprite");
setSize(800, 800);
setLocationRelativeTo(null);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
TheGame ex = new TheGame();
ex.setVisible(true);
});
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 269 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 738 B

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="output" path="bin"/>
</classpath>

View File

@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>Game-3</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

Binary file not shown.

After

Width:  |  Height:  |  Size: 269 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 738 B

View File

@@ -0,0 +1,109 @@
package Game;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.List;
import javax.swing.Timer;
import javax.swing.JPanel;
public class Board extends JPanel implements ActionListener {
private final int ICRAFT_X = 40;
private final int ICRAFT_Y = 60;
private final int DELAY = 10;
private Timer timer;
private SpaceShip spaceShip;
public Board() {
initBoard();
}
private void initBoard() {
addKeyListener(new TAdapter());
setBackground(Color.BLACK);
setFocusable(true);
spaceShip = new SpaceShip(ICRAFT_X, ICRAFT_Y);
timer = new Timer(DELAY, this);
timer.start();
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
doDrawing(g);
Toolkit.getDefaultToolkit().sync();
}
private void doDrawing(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(spaceShip.getImage(), spaceShip.getX(),
spaceShip.getY(), this);
List<Missile> missiles = spaceShip.getMissiles();
for (Missile missile : missiles) {
g2d.drawImage(missile.getImage(), missile.getX(),
missile.getY(), this);
}
}
@Override
public void actionPerformed(ActionEvent e) {
updateMissiles();
updateSpaceShip();
repaint();
}
private void updateMissiles() {
List<Missile> missiles = spaceShip.getMissiles();
for (int i = 0; i < missiles.size(); i++) {
Missile missile = missiles.get(i);
if (!missile.active) {
missiles.remove(i);
}
}
}
private void updateSpaceShip() {
spaceShip.move();
}
private class TAdapter extends KeyAdapter {
@Override
public void keyReleased(KeyEvent e) {
spaceShip.keyReleased(e);
}
@Override
public void keyPressed(KeyEvent e) {
spaceShip.keyPressed(e);
}
}
}

View File

@@ -0,0 +1,32 @@
// Origin: https://zetcode.com/javagames/movingsprites/
package Game;
public class Missile extends Sprite {
private final int BOARD_WIDTH = 800;
private final int MISSILE_SPEED = 2;
public Missile(int x, int y) {
super(x, y);
initMissile();
MissileThread myMissile = new MissileThread( this, 1, 0, 800, 800 );
myMissile.start();
}
private void initMissile() {
loadImage("src/resources/missile.png");
getImageDimensions();
}
// public void move() {
//
// x += MISSILE_SPEED;
//
// if (x > BOARD_WIDTH) {
// visible = false;
// }
// }
}

View File

@@ -0,0 +1,35 @@
package Game;
public class MissileThread extends Thread {
private Missile myMissile;
private int Xspeed, Yspeed, MaxX, MaxY;
public MissileThread(Missile theMissile, int theXspeed, int theYspeed, int maxX, int maxY) {
myMissile = theMissile;
Xspeed = theXspeed;
Yspeed = theYspeed;
MaxX = maxX;
MaxY = maxY;
}
public void run() {
System.out.println("Missile started");
try {
while (true) {
Thread.sleep(10);
myMissile.x += Xspeed;
myMissile.y += Yspeed;
if ((myMissile.x > MaxX) || (myMissile.y > MaxY)) {
myMissile.active = false;
// Die die die
System.out.println("Missile died");
break;
}
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

View File

@@ -0,0 +1,87 @@
// Origin: https://zetcode.com/javagames/movingsprites/
package Game;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;
public class SpaceShip extends Sprite {
private int dx;
private int dy;
private List<Missile> missiles;
public SpaceShip(int x, int y) {
super(x, y);
initSpaceShip();
}
private void initSpaceShip() {
missiles = new ArrayList<>();
loadImage("src/resources/spaceship.png");
getImageDimensions();
}
public void move() {
x += dx;
y += dy;
}
public List<Missile> getMissiles() {
return missiles;
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_SPACE) {
fire();
}
if (key == KeyEvent.VK_LEFT) {
dx = -1;
}
if (key == KeyEvent.VK_RIGHT) {
dx = 1;
}
if (key == KeyEvent.VK_UP) {
dy = -1;
}
if (key == KeyEvent.VK_DOWN) {
dy = 1;
}
}
public void fire() {
missiles.add(new Missile(x + width, y + height / 2));
}
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT) {
dx = 0;
}
if (key == KeyEvent.VK_RIGHT) {
dx = 0;
}
if (key == KeyEvent.VK_UP) {
dy = 0;
}
if (key == KeyEvent.VK_DOWN) {
dy = 0;
}
}
}

View File

@@ -0,0 +1,56 @@
// Origin: https://zetcode.com/javagames/movingsprites/
package Game;
import java.awt.Image;
import javax.swing.ImageIcon;
public class Sprite {
protected int x;
protected int y;
protected int width;
protected int height;
protected boolean active;
protected Image image;
public Sprite(int x, int y) {
this.x = x;
this.y = y;
active = true;
}
protected void loadImage(String imageName) {
ImageIcon ii = new ImageIcon(imageName);
image = ii.getImage();
}
protected void getImageDimensions() {
width = image.getWidth(null);
height = image.getHeight(null);
}
public Image getImage() {
return image;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public boolean isActive() {
return active;
}
public void setActive(Boolean active) {
this.active = active;
}
}

View File

@@ -0,0 +1,35 @@
// Origin: https://zetcode.com/javagames/movingsprites/
package Game;
import java.awt.EventQueue;
import javax.swing.JFrame;
public class TheGame extends JFrame {
public TheGame() {
initUI();
}
private void initUI() {
add(new Board());
setTitle("Moving sprite");
setSize(800, 800);
setLocationRelativeTo(null);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
TheGame ex = new TheGame();
ex.setVisible(true);
});
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 269 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 738 B

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8"/>
<classpathentry kind="src" path="src"/>
<classpathentry kind="output" path="bin"/>
</classpath>

View File

@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>MonitorCase1</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

View File

@@ -0,0 +1,11 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=1.8
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.source=1.8

View File

@@ -0,0 +1,28 @@
public class Buffer {
private char[] buffer;
private int count = 0, in = 0, out = 0;
Buffer(int size) {
buffer = new char[size];
}
public synchronized void Put(char c) {
while (count == buffer.length)
;
System.out.println("Producing " + c + " ...");
buffer[in] = c;
in = (in + 1) % buffer.length;
count++;
}
public synchronized char Get() {
while (count == 0)
;
char c = buffer[out];
out = (out + 1) % buffer.length;
count--;
System.out.println("Consuming " + c + " ...");
return c;
}
}

View File

@@ -0,0 +1,28 @@
/*
* Run this code.
* 1: What happens ?
* 2: Why does it happen ?
*
* Code courtesy of www.csc.villanova.edu/~mdamian/threads/javamonitors.html
*/
public class PC {
public static void main(String[] args) {
Buffer b = new Buffer(4);
Producer p = new Producer(b);
Consumer c = new Consumer(b);
p.start();
c.start();
try {
p.join();
c.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("End");
}
}

View File

@@ -0,0 +1,27 @@
class Producer extends Thread {
private Buffer buffer;
Producer(Buffer b) {
buffer = b;
}
public void run() {
for (int i = 0; i < 10; i++) {
buffer.Put((char) ('A' + i % 26));
}
}
}
class Consumer extends Thread {
private Buffer buffer;
Consumer(Buffer b) {
buffer = b;
}
public void run() {
for (int i = 0; i < 10; i++) {
buffer.Get();
}
}
}

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8"/>
<classpathentry kind="src" path="src"/>
<classpathentry kind="output" path="bin"/>
</classpath>

View File

@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>MonitorCase2</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

View File

@@ -0,0 +1,11 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=1.8
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.source=1.8

View File

@@ -0,0 +1,40 @@
public class Buffer {
private char[] buffer;
private int count = 0, in = 0, out = 0;
Buffer(int size) {
buffer = new char[size];
}
public synchronized void Put(char c) {
while (count == buffer.length) {
try {
wait();
} catch (InterruptedException e) {
} finally {
}
}
System.out.println("Producing " + c + " ...");
buffer[in] = c;
in = (in + 1) % buffer.length;
count++;
notify();
}
public synchronized char Get() {
while (count == 0) {
try {
wait();
} catch (InterruptedException e) {
} finally {
}
}
char c = buffer[out];
out = (out + 1) % buffer.length;
count--;
System.out.println("Consuming " + c + " ...");
notify();
return c;
}
}

View File

@@ -0,0 +1,50 @@
/*
* In MonitorCase1, the producer thread quickly fills the buffer
* with characters and then waits for the consumer to consume
* some characters from the buffer. The problem is that the
* producer waits inside the monitor associated with the buffer,
* preventing the consumer to execute the synchronized Get
* method on the buffer.
*
* We really want the Producer to release the monitor if the
* buffer becomes full and allow the Consumer to proceed.
* Similarly, the Consumer must release the monitor if the
* buffer becomes empty and allow the Producer to proceed.
* To coordinate the two threads, we must use the Object's
* wait() and notify or notifyAll() methods.
*
* The wait() method suspends the calling thread and temporarily
* releases ownership of the monitor (so it allows other threads
* to acquire the monitor). The suspended thread that called
* wait() wakes up only when another thread calls notify() or
* notifyAll() on that object.
*
* The notifyAll() method wakes up all threads waiting on the
* object in question. The awakened threads compete for the
* monitor. One thread gets it, and the others go back to
* waiting.
*
* Code courtesy of www.csc.villanova.edu/~mdamian/threads/javamonitors.html
*/
public class PC {
public static void main(String[] args) {
Buffer b = new Buffer(4);
Producer p = new Producer(b);
Consumer c = new Consumer(b);
p.start();
c.start();
try {
p.join();
c.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("End...");
}
}

View File

@@ -0,0 +1,27 @@
class Producer extends Thread {
private Buffer buffer;
Producer(Buffer b) {
buffer = b;
}
public void run() {
for (int i = 0; i < 10; i++) {
buffer.Put((char) ('A' + i % 26));
}
}
}
class Consumer extends Thread {
private Buffer buffer;
Consumer(Buffer b) {
buffer = b;
}
public void run() {
for (int i = 0; i < 10; i++) {
buffer.Get();
}
}
}

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="output" path="bin"/>
</classpath>

View File

@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>NioLineCount</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,93 @@
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.charset.Charset;
import java.nio.file.OpenOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.concurrent.Semaphore;
/**
*
*/
/**
* @author KAJE
*
*/
public class NioLineCount {
static int theCount = 0;
// A 0 means that you will be waited until signalled
static Semaphore partialReadGate = new Semaphore(1);
static boolean doContinue = true;
static long readPosition = 0;
private static int lineCount(String thePath, boolean doDance){
if ( ! doDance ) return -1;
ByteBuffer buffer = ByteBuffer.allocate(1024);
Path myPath = Paths.get( thePath );
try {
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(myPath, StandardOpenOption.READ);
while ( doContinue ) {
try {
// In the end we will be waiting here
partialReadGate.acquire();
if ( ! doContinue ) return theCount;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
fileChannel.read(buffer, readPosition, buffer, new CompletionHandler<Integer,ByteBuffer>() {
@Override
public void completed(Integer result, ByteBuffer attachment) {
// System.out.println("Result = " + result + " Limit = " + attachment.limit());
if ( result != -1 ) {
attachment.flip();
byte[] data = new byte[attachment.limit()];
attachment.get( data );
//System.out.println(new String(data));
for (int i = 0; i < data.length; i++ ) {
if ( data[i] == '\n' )
theCount++;
//System.out.println("data: " + data[i]);
}
// System.out.println("position: " + readPosition + " Count: " + theCount);
readPosition += data.length;
attachment.clear();
} else {
doContinue = false;
}
partialReadGate.release();
}
@Override
public void failed(Throwable exc, ByteBuffer attachment) {
}
});
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return theCount;
}
/**
* @param args
*/
public static void main(String[] args){
long startTime = System.nanoTime();
lineCount("", false);
long dryRun = System.nanoTime() - startTime;
startTime = System.nanoTime();
int lines = lineCount("input.txt", true);
long stopTime = System.nanoTime();
System.out.println("Lines: " + String.valueOf(lines));
System.out.println("Time it took: " + (stopTime - startTime - dryRun) + " " + dryRun);
}
}

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="output" path="bin"/>
</classpath>

View File

@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>ProcessDemo</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

View File

@@ -0,0 +1,17 @@
import java.io.IOException;
public class ProcessDemo {
// You will have to find your own application path for this
public static void main(String[] args) {
ProcessBuilder builder = new ProcessBuilder("C:\\Program Files\\HeidiSQL\\heidisql.exe");
try {
Process process = builder.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Done...");
}
}

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8"/>
<classpathentry kind="src" path="src"/>
<classpathentry kind="output" path="bin"/>
</classpath>

View File

@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>SemaphoreDemo</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

View File

@@ -0,0 +1,11 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=1.8
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.source=1.8

View File

@@ -0,0 +1,88 @@
// java program to demonstrate
// use of semaphores Locks
import java.util.concurrent.*;
//A shared resource/class.
class Shared
{
static int count = 0;
}
class MyThread extends Thread
{
// We need 2 semaphores.
// This one will prevent the Producer writing twice
Semaphore semPro;
// This one will prevent the consumer reading twice
Semaphore semCon;
String threadName;
public MyThread(Semaphore mySemPro, Semaphore mySemCon, String threadName)
{
super(threadName);
// We set the semaphores from the main method
this.semPro = mySemPro;
this.semCon = mySemCon;
this.threadName = threadName;
}
@Override
public void run()
{
// run by thread "Producer"
if(this.getName().equals("Producer"))
{
System.out.println("Starting " + threadName);
for ( int i=0; i<5; i++)
{
try
{
// Wait until we may write (initially we are allowed)
// coming back here - we must wait for the "Consumer" to read
semPro.acquire();
Shared.count++;
System.out.println(threadName + " Writes: " + Shared.count);
// Signal the "Consumer" that a value is ready
semCon.release();
// Now, allowing a context switch -- if possible.
// for thread Consumer to execute
Thread.sleep(10);
}
catch (InterruptedException exc)
{
// Should anything fail - then we end up here
System.out.println(exc);
}
}
// And we are done
System.out.println("Ending " + threadName);
}
// run by thread Consumer
else
{
System.out.println("Starting " + threadName);
for (int i=0; i< 5; i++)
{
try
{
// Waiting for a value to be present (initially: Wait)
semCon.acquire();
System.out.println(threadName + " Reads: " + Shared.count);
// Signal the "Producer" that the value was read, so the buffer is now cleared
semPro.release();
}
catch (InterruptedException exc)
{
// Should we fail - here we go
System.out.println(exc);
}
}
// And we are done
System.out.println("Ending " + threadName);
}
}
}

View File

@@ -0,0 +1,35 @@
// java program to demonstrate
// use of semaphores Locks
import java.util.concurrent.*;
// Driver class
public class SemaphoreDemo
{
public static void main(String args[]) throws InterruptedException
{
// creating a Semaphore object
// A 1 means that you are allowed 1 write to start with
Semaphore semPro = new Semaphore(1);
// A 0 means that you are not allowed to read (as nobody has yet written to the buffer)
Semaphore semCon = new Semaphore(0);
// creating two threads with name A and B
// Note that thread A will increment the count
// and thread B will decrement the count
MyThread mt1 = new MyThread(semPro, semCon, "Producer");
MyThread mt2 = new MyThread(semPro, semCon, "Consumer");
// stating threads A and B
mt1.start();
mt2.start();
// waiting for threads A and B
mt1.join();
mt2.join();
// count will always remain 0 after
// both threads will complete their execution
System.out.println("count: " + Shared.count);
}
}

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="output" path="bin"/>
</classpath>

View File

@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>ThreadsDemo</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

View File

@@ -0,0 +1,26 @@
//
// Demo of thread starting a thread
//
public class Level1Interface implements Runnable {
private String MyString;
public Level1Interface(String InitString) {
MyString = InitString;
}
@Override
public void run() {
System.out.println(MyString + " Interface");
ThreadsExtend myThreadA = new ThreadsExtend( MyString + "A" );
myThreadA.start();
try {
myThreadA.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(MyString + " Interface...Done");
}
}

View File

@@ -0,0 +1,34 @@
public class ThreadsDemo {
public static void main(String[] args) {
ThreadsExtend myThreadA = new ThreadsExtend("A");
ThreadsExtend myThreadB = new ThreadsExtend("B");
ThreadsExtend myThreadC = new ThreadsExtend("C");
Runnable myRunnableD = new ThreadsInterface("D");
Runnable myRunnableE = new ThreadsInterface("E");
Runnable myRunnableF = new Level1Interface("F");
myThreadA.start();
myThreadB.start();
myThreadC.start();
Thread myThreadD = new Thread( myRunnableD );
myThreadD.start();
Thread myThreadE = new Thread( myRunnableE );
myThreadE.start();
Thread myThreadF = new Thread( myRunnableF );
myThreadF.start();
try {
myThreadA.join();
myThreadB.join();
myThreadC.join();
myThreadD.join();
myThreadE.join();
myThreadF.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Main Done...");
}
}

View File

@@ -0,0 +1,20 @@
public class ThreadsExtend extends Thread {
private String MyString;
public ThreadsExtend ( String InitString ) {
MyString = InitString;
}
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(MyString + " running");
}
}

View File

@@ -0,0 +1,15 @@
public class ThreadsInterface implements Runnable {
private String MyString;
public ThreadsInterface(String InitString) {
MyString = InitString;
}
@Override
public void run() {
System.out.println(MyString + " Interface");
}
}