Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Родин Отчет 3.docx
Скачиваний:
10
Добавлен:
09.02.2015
Размер:
174.14 Кб
Скачать

Листинги программ

Main class

package Main;

import java.io.FileNotFoundException;

import java.io.PrintWriter;

import java.util.Formatter;

import java.util.Random;

/**

* Created by Кирилл on 05.05.2014.

*/

class NewThread implements Runnable

{

Thread thread;

String name;

double matrix[][];

int number;

NewThread(String name, double matrix[][], int number)

{

this.name=name;

this.matrix=matrix;

this.number=number;

thread=new Thread(this,name);

thread.start();

}

public void run()

{

Random rand = new Random();

for(int i=number; i<matrix.length; i+=2)

{

for(int j=0; j<matrix[i].length; j++)

{

matrix[i][j]= -50 + rand.nextDouble()*100;

//System.out.println(name + ":" + matrix[i][j]);

}

}

}

}

public class MainClass {

public static void main(String args[]) throws FileNotFoundException {

double matrix[][]=new double[50][50];

PrintWriter writer = new PrintWriter("info.txt");

PrintWriter writerOne =new PrintWriter("infoOnOneThread.txt");

Formatter fmt;

long start=System.nanoTime();

new NewThread("Один",matrix,0);

new NewThread("Два",matrix,1);

long end=System.nanoTime();

try

{

Thread.sleep(1000);

}

catch (InterruptedException e)

{

System.out.println("Главный поток прерван");

}

for(int i = 0; i<matrix.length; i++)

{

fmt = new Formatter();

for (int j = 0; j < matrix[i].length; j++)

{

fmt.format("|% 10.4f ", matrix[i][j]);

}

writer.print(fmt);

fmt.close();

writer.println();

}

writer.println("Время затраченное при двух потоках на генерацию матрицы: " + (end-start) + " ns");

Random rand = new Random();

start=System.nanoTime();

for(int i=0; i<matrix.length; i++)

{

for(int j=0; j<matrix[i].length; j++)

{

matrix[i][j]= -50 + rand.nextDouble()*100;

}

}

end=System.nanoTime();

for(int i = 0; i<matrix.length; i++)

{

fmt = new Formatter();

for (int j = 0; j < matrix[i].length; j++)

{

fmt.format("|% 10.4f ", matrix[i][j]);

}

writerOne.print(fmt);

fmt.close();

writerOne.println();

}

writerOne.println("Время затраченное при одном потоке на генерацию матрицы: " + (end-start) + " ns");

writer.close();

writerOne.close();

}

}

New Thread.java

package Main;

import java.io.FileNotFoundException;

import java.io.PrintWriter;

import java.util.Formatter;

import java.util.Random;

/**

* Created by Кирилл on 05.05.2014.

*/

class NewThread implements Runnable

{

Thread thread;

String name;

double matrix[][];

int number;

NewThread(String name, double matrix[][], int number)

{

this.name=name;

this.matrix=matrix;

this.number=number;

thread=new Thread(this,name);

thread.start();

}

public void run()

{

Random rand = new Random();

for(int i=number; i<matrix.length; i+=2)

{

for(int j=0; j<matrix[i].length; j++)

{

matrix[i][j]= -50 + rand.nextDouble()*100;

//System.out.println(name + ":" + matrix[i][j]);

}

}

}

}

public class MainClass {

public static void main(String args[]) throws FileNotFoundException {

double matrix[][]=new double[50][50];

PrintWriter writer = new PrintWriter("info.txt");

PrintWriter writerOne =new PrintWriter("infoOnOneThread.txt");

Formatter fmt;

long start=System.nanoTime();

new NewThread("Один",matrix,0);

new NewThread("Два",matrix,1);

long end=System.nanoTime();

try

{

Thread.sleep(1000);

}

catch (InterruptedException e)

{

System.out.println("Главный поток прерван");

}

for(int i = 0; i<matrix.length; i++)

{

fmt = new Formatter();

for (int j = 0; j < matrix[i].length; j++)

{

fmt.format("|% 10.4f ", matrix[i][j]);

}

writer.print(fmt);

fmt.close();

writer.println();

}

writer.println("Время затраченное при двух потоках на генерацию матрицы: " + (end-start) + " ns");

Random rand = new Random();

start=System.nanoTime();

for(int i=0; i<matrix.length; i++)

{

for(int j=0; j<matrix[i].length; j++)

{

matrix[i][j]= -50 + rand.nextDouble()*100;

}

}

end=System.nanoTime();

for(int i = 0; i<matrix.length; i++)

{

fmt = new Formatter();

for (int j = 0; j < matrix[i].length; j++)

{

fmt.format("|% 10.4f ", matrix[i][j]);

}

writerOne.print(fmt);

fmt.close();

writerOne.println();

}

writerOne.println("Время затраченное при одном потоке на генерацию матрицы: " + (end-start) + " ns");

writer.close();

writerOne.close();

}

}

2

Music.java

package main;

public class Music {

private int id;

private String genre;

private String performer;

private String name;

private int year;

public Music(int id, String genre, String performer, String name, int year) {

this.id = id;

this.genre = genre;

this.performer = performer;

this.name = name;

this.year= year;

}

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

public String getGenre() {

return genre;

}

public void setGenre(String genre) {

this.genre = genre;

}

public String getPerformer() {

return performer;

}

public void setPerformer(String performer) {

this.performer = performer;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public int getYear() {

return year;

}

public void setYear(int year) {

this.year = year;

}

}

MusicDAO.java

package main;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.util.ArrayList;

import java.util.List;

public class MusicDAO {

// Вспомогательный метод получения соединения

private Connection getConnection() throws Exception {

// Подгрузка драйвера БД Derby

Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();

// Получение соединения с БД

return DriverManager.getConnection("jdbc:derby:/firstDb;create=true");

}

public List<Integer> getMusicIds() throws Exception {

List<Integer> musicIds = new ArrayList<Integer>();

// Получение соединения с БД

Connection con = getConnection();

// Выполнение SQL-запроса

ResultSet rs = con.createStatement().executeQuery("Select ID From discs");

// Перечисляем результаты выборки

while (rs.next()) {

// Из каждой строки выборки выбираем

// результат и помещаем в коллекцию

musicIds.add(rs.getInt(1));

}

// Закрываем выборку и соединение с БД

rs.close();

con.close();

return musicIds;

}

/**

* Возвращает музыку по идентификатору

*

* @return

*/

public List<Music> getMusicById(int id) throws Exception {

List<Music> musics = new ArrayList<Music>();

// Получение соединения с БД

Connection con = getConnection();

// Подготовка SQL-запроса

PreparedStatement st = con.prepareStatement(

"Select genre, performer, name, years " +

"From discs " +

"Where ID = ?");

// Указание значений параметров запроса

st.setInt(1, id);

// Выполнение запроса

ResultSet rs = st.executeQuery();

Music music = null;

// Перечисляем результаты выборки

while (rs.next()) {

// Из каждой строки выборки выбираем результаты,

// формируем новый объект Music

// и помещаем его в коллекцию

music = new Music(

id,

rs.getString(1),

rs.getString(2),

rs.getString(3),

rs.getInt(4));

musics.add(music);

}

// Закрываем выборку и соединение с БД

rs.close();

con.close();

return musics;

}

/**

* Добавляет новую музыку

* @param music

* @throws Exception

*/

public void addMusic(Music music) throws Exception {

// Получение соединения с БД

Connection con = getConnection();

// Подготовка SQL-запроса

PreparedStatement st = con.prepareStatement(

"Insert into discs " +

"(id, genre, performer, name, years) " +

"values (?, ?, ?, ?, ?)");

// Указание значений параметров запроса

st.setInt(1, music.getId());

st.setString(2, music.getGenre());

st.setString(3, music.getPerformer());

st.setString(4, music.getName());

st.setInt(5, music.getYear());

// Выполнение запроса

st.executeUpdate();

con.close();

}

/**

* Обновляет данные о товаре

* @param music

* @throws Exception

*/

public void setMusic(Music music) throws Exception {

// Получение соединения с БД

Connection con = getConnection();

// Подготовка SQL-запроса

PreparedStatement st = con.prepareStatement(

"Update discs " +

"Set genre=?, performer=?, name=?, years=?" +

"Where id=?");

// Указание значений параметров запроса

st.setString(1, music.getGenre());

st.setString(2, music.getPerformer());

st.setString(3, music.getName());

st.setInt(4, music.getYear());

st.setInt(5, music.getId());

// Выполнение запроса

st.executeUpdate();

con.close();

}

public void removeMusic(int id) throws Exception {

// Получение соединения с БД

Connection con = getConnection();

// Подготовка SQL-запроса

PreparedStatement st = con.prepareStatement(

"Delete from discs " +

"Where id = ?");

// Указание значений параметров запроса

st.setInt(1, id);

// Выполнение запроса

st.executeUpdate();

con.close();

}

public List<Music> getAllDiscs() throws Exception {

List<Music> discs = new ArrayList<Music>();

// Получение соединения с БД

Connection con = getConnection();

// Подготовка SQL-запроса

PreparedStatement st = con.prepareStatement("Select id, genre,performer, name, years From discs");

// Указание значений параметров запроса

// Выполнениезапроса

ResultSet rs = st.executeQuery();

Music currentMusic = null;

// Перечисляем результаты выборки

while (rs.next()) {

// Из каждой строки выборки выбираем результаты,

// формируем новый объект Product

// и помещаем его в коллекцию

currentMusic = new Music(

rs.getInt(1),

rs.getString(2),

rs.getString(3),

rs.getString(4),

rs.getInt(5));

discs.add(currentMusic);

}

// Закрываем выборку и соединение с БД

rs.close();

con.close();

return discs;

}

public List<Music> getMusicByGenre(String genre) throws Exception {

List<Music> discs = new ArrayList<Music>();

// Получение соединения с БД

Connection con = getConnection();

// Подготовка SQL-запроса

PreparedStatement st = con.prepareStatement(

"Select id, performer, name, years " +

"From discs " +

"Where genre= ?");

// Указание значений параметров запроса

st.setString(1,genre);

// Выполнениезапроса

ResultSet rs = st.executeQuery();

Music currentDisc = null;

// Перечисляем результаты выборки

while (rs.next()) {

// Из каждой строки выборки выбираем результаты,

// формируем новый объект Product

// и помещаем его в коллекцию

currentDisc = new Music(

rs.getInt(1),

genre,

rs.getString(2),

rs.getString(3),

rs.getInt(4));

discs.add(currentDisc);

}

// Закрываем выборку и соединение с БД

rs.close();

con.close();

return discs;

}

public List<String> getMusicGenre() throws Exception {

List<String> genres = new ArrayList<String>();

// Получение соединения с БД

Connection con = getConnection();

// Выполнение SQL-запроса

ResultSet rs = con.createStatement().executeQuery("Select distinct genre From discs");

// Перечисляем результаты выборки

while (rs.next()) {

// Из каждой строки выборки выбираем

// результат и помещаем в коллекцию

genres.add(rs.getString(1));

}

// Закрываем выборку и соединение с БД

rs.close();

con.close();

return genres;

}

public List<Music> getMusicByName(String name) throws Exception {

List<Music> discs = new ArrayList<Music>();

// Получение соединения с БД

Connection con = getConnection();

// Подготовка SQL-запроса

PreparedStatement st = con.prepareStatement(

"Select id, genre, performer, years " +

"From discs " +

"Where name= ?");

// Указание значений параметров запроса

st.setString(1,name);

// Выполнениезапроса

ResultSet rs = st.executeQuery();

Music currentDisc = null;

// Перечисляем результаты выборки

while (rs.next()) {

// Из каждой строки выборки выбираем результаты,

// формируем новый объект Product

// и помещаем его в коллекцию

currentDisc = new Music(

rs.getInt(1),

rs.getString(2),

rs.getString(3),

name,

rs.getInt(4));

discs.add(currentDisc);

}

// Закрываем выборку и соединение с БД

rs.close();

con.close();

return discs;

}

public List<String> getMusicNames() throws Exception {

List<String> genres = new ArrayList<String>();

// Получение соединения с БД

Connection con = getConnection();

// Выполнение SQL-запроса

ResultSet rs = con.createStatement().executeQuery("Select name From discs");

// Перечисляем результаты выборки

while (rs.next()) {

// Из каждой строки выборки выбираем

// результат и помещаем в коллекцию

genres.add(rs.getString(1));

}

// Закрываем выборку и соединение с БД

rs.close();

con.close();

return genres;

}

}

MusicInfo.java

package main;

import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

public class MusicInfo extends JDialog {

private static final long serialVersionUID = 1L;

// Создаем DAO-объект

MusicDAO musicDAO = new MusicDAO();

// Объявление элементов управления

private JLabel lbSelectId = new JLabel("Выбор товара по id");

private JLabel lbId = new JLabel("Id");

private JLabel lbSelectGenre = new JLabel("Жанр");

private JLabel lbPerf = new JLabel("Исполнитель");

private JLabel lbName = new JLabel("Название");

private JLabel lbYear = new JLabel("Год");

private JLabel lbGenre = new JLabel("Выбор жанра");

private JComboBox comboId = new JComboBox();

private JComboBox comboGenre = new JComboBox();

private JTextField txtId = new JTextField();

private JTextField txtGenre = new JTextField();

private JTextField txtPerf = new JTextField();

private JTextField txtName = new JTextField();

private JTextField txtYear = new JTextField();

private JButton btnAdd = new JButton("Добавить");

private JButton btnUpdate = new JButton("Обновить");

private JButton btnRemove = new JButton("Удалить");

private JButton btnClear = new JButton("Очистить");

private JButton btnShowAll = new JButton("Показать все диски");

private JButton btnShowByGenre = new JButton("Показать диски по жанру");

/**

* Создает экземпляр диалога

* @param args

*/

public static void main(String[] args) {

new MusicInfo();

}

/**

* Конструктор диалога

*/

public MusicInfo() {

this.setTitle("Информация о музыкальных дисках");

this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);

this.setLayout(new GridLayout(12, 2));

this.setBounds(100, 50, 500, 300);

// Добавление элементов управления в диалог

this.add(lbSelectGenre);

this.add(comboGenre);

this.add(lbSelectId);

this.add(comboId);

this.add(lbId);

this.add(txtId);

this.add(lbGenre);

this.add(txtGenre);

this.add(lbPerf);

this.add(txtPerf);

this.add(lbName);

this.add(txtName);

this.add(lbYear);

this.add(txtYear);

this.add(btnAdd);

this.add(btnUpdate);

this.add(btnRemove);

this.add(btnClear);

this.add(btnShowAll);

this.add(btnShowByGenre);

// Описание обработчиков событий

comboId.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

showMusicData();

}

});

btnShowAll.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

createGUI1();

}

});

btnShowByGenre.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

createGUI2();

}

});

btnAdd.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

addMusic();

}

});

btnUpdate.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

updateMusic();

}

});

btnRemove.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

removeMusic();

}

});

btnClear.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

clearMusicInfo();

}

});

// Обновляем список идентификаторов дисков

refreshIdList();

refreshGenreList();

// Отображаем диалог на экране

this.setVisible(true);

}

/**

* Считывает список идентификаторов дисков

* и заполняет список

*/

private void refreshIdList() {

try {

// получаем список идентификаторов

java.util.List<String> MusicIds = musicDAO.getMusicNames();

// очищаем список

comboId.removeAllItems();

// заполняем список полученными данными

for (String MusicId: MusicIds) {

comboId.addItem(MusicId);

}

} catch (Exception e) {

e.printStackTrace();

JOptionPane.showMessageDialog(this, e.getMessage());

}

}

private void refreshGenreList() {

try {

// получаем список идентификаторов

java.util.List<String> genres = musicDAO.getMusicGenre();

// очищаем список

comboGenre.removeAllItems();

// заполняем список полученными данными

for (String genre: genres) {

comboGenre.addItem(genre);

}

} catch (Exception e) {

e.printStackTrace();

JOptionPane.showMessageDialog(this, e.getMessage());

}

}

/**

* Отображает данные о музыке по

* выбранному в списке идентификатору

*/

private void createGUI2()

{

JFrame.setDefaultLookAndFeelDecorated(true);

JFrame frame = new JFrame("Музыка по жанру");

frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

Object[] columnNames = {"Id", "Исполнитель","Название","Год выхода"};

try {

java.util.List<Music> discs = musicDAO.getMusicByGenre((String) comboGenre.getSelectedItem());

String [][] strstrdiscs = new String[discs.size()][4];

for(int i=0;i<discs.size();i++) {

strstrdiscs[i][0]=Integer.toString(discs.get(i).getId());

strstrdiscs[i][1]=discs.get(i).getPerformer();

strstrdiscs[i][2]=discs.get(i).getName();

strstrdiscs[i][3]=Integer.toString(discs.get(i).getYear());

}

JTable jTable = new JTable(strstrdiscs, columnNames);

JScrollPane jscrlp = new JScrollPane(jTable);

frame.getContentPane().add(jscrlp);

}

catch (Exception e) {

e.printStackTrace();

JOptionPane.showMessageDialog(this, e.getMessage());

}

//Создаём таблицу

frame.setPreferredSize(new Dimension(500, 500));

frame.pack();

frame.setVisible(true);

}

private void createGUI1() {

JFrame.setDefaultLookAndFeelDecorated(true);

JFrame frame = new JFrame("Все диски");

frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

Object[] columnNames = {"Id", "Жанр", "Исполнитель","Название", "Год выхода"};

try {

java.util.List<Music> musicList = musicDAO.getAllDiscs();

String [][] strMusic = new String[musicList.size()][5];

for(int i=0;i<musicList.size();i++) {

strMusic[i][0]=Integer.toString(musicList.get(i).getId());

strMusic[i][1]=musicList.get(i).getGenre();

strMusic[i][2]=musicList.get(i).getPerformer();

strMusic[i][3]=musicList.get(i).getName();

strMusic[i][4]=Integer.toString(musicList.get(i).getYear());

}

JTable jTable = new JTable(strMusic, columnNames);

JScrollPane jscrlp = new JScrollPane(jTable);

frame.getContentPane().add(jscrlp);

}

catch (Exception e) {

e.printStackTrace();

JOptionPane.showMessageDialog(this, e.getMessage());

}

//Создаём таблицу

frame.setPreferredSize(new Dimension(500, 500));

frame.pack();

frame.setVisible(true);

}

protected void showMusicData() {

try {

// забираем значение, выбранное в списке

// идентификаторов товаров

String musicName = (String)comboId.getSelectedItem();

if (musicName != null) {

// получаем товар по идентификатору

java.util.List<Music> music = musicDAO.getMusicByName(musicName);

// заполняем текстовые поля значениями

// параметров товара

for(int i=0; i<music.size(); i++){

txtId.setText(String.valueOf(music.get(i).getId()));

txtGenre.setText(music.get(i).getGenre());

txtPerf.setText(music.get(i).getPerformer());

txtName.setText(music.get(i).getName());

txtYear.setText(String.valueOf(music.get(i).getYear()));

}

}

} catch (Exception e) {

e.printStackTrace();

JOptionPane.showMessageDialog(this, e.getMessage());

}

}

/**

* Добавляет новую музыку на основе

* данных текстовых полей

*/

protected void addMusic() {

try {

// создаем новый объект-товар

// на основе данных диалога

Music music = new Music(

Integer.parseInt(txtId.getText()),

txtGenre.getText(),

txtPerf.getText(),

txtName.getText(),

Integer.parseInt(txtYear.getText()));

// сохраняем товар в БД

musicDAO.addMusic(music);

// обновляем список идентификаторов

refreshIdList();

refreshGenreList();

// устанавливаем текущим добавленный товар

comboId.setSelectedItem(Integer.parseInt(txtId.getText()));

} catch (Exception e) {

e.printStackTrace();

JOptionPane.showMessageDialog(this, e.getMessage());

}

}

/**

* Обновляет информацию о музыке на основе

* данных текстовых полей

*/

protected void updateMusic() {

try {

// формируем объект-товар

// на основе данных диалога

Music music = new Music(

Integer.parseInt(txtId.getText()),

txtGenre.getText(),

txtPerf.getText(),

txtName.getText(),

Integer.parseInt(txtYear.getText()));

// обновляем данные о товаре в БД

musicDAO.setMusic(music);

} catch (Exception e) {

e.printStackTrace();

JOptionPane.showMessageDialog(this, e.getMessage());

}

}

/**

* Удаляет выбранный товар

*/

protected void removeMusic() {

try {

// удаляем товар из БД

musicDAO.removeMusic(Integer.parseInt(txtId.getText()));

// обновляем список идентификаторов товаров

refreshIdList();

// отображаем данные по первому товару в списке

showMusicData();

} catch (Exception e) {

e.printStackTrace();

JOptionPane.showMessageDialog(this, e.getMessage());

}

}

/**

* Очищает данные в текстовых полях

*/

protected void clearMusicInfo() {

try {

txtId.setText("");

txtGenre.setText("");

txtPerf.setText("");

txtName.setText("");

txtYear.setText("");

} catch (Exception e) {

e.printStackTrace();

JOptionPane.showMessageDialog(this, e.getMessage());

}

}

}

Script.sql

-- подключение

connect 'jdbc:derby:/firstDb;create=true';

--drop table MUSIC;

-- создание таблицы

create table discs(id integer primary key not null , genre varchar(100), performer varchar(100), name varchar(100), years integer);

-- отключение и выход

disconnect;

exit;

Выводы

В ходе лабораторной работы были изучены основы работы с потоками выполнения приложения, базами данных, компонентами Swing создания пользовательского интерфейса, также ознакомился на практике с реализацией механизмов работы с базами данных, создания простейшего интерфейса пользователя.