Студопедия

КАТЕГОРИИ:


Архитектура-(3434)Астрономия-(809)Биология-(7483)Биотехнологии-(1457)Военное дело-(14632)Высокие технологии-(1363)География-(913)Геология-(1438)Государство-(451)Демография-(1065)Дом-(47672)Журналистика и СМИ-(912)Изобретательство-(14524)Иностранные языки-(4268)Информатика-(17799)Искусство-(1338)История-(13644)Компьютеры-(11121)Косметика-(55)Кулинария-(373)Культура-(8427)Лингвистика-(374)Литература-(1642)Маркетинг-(23702)Математика-(16968)Машиностроение-(1700)Медицина-(12668)Менеджмент-(24684)Механика-(15423)Науковедение-(506)Образование-(11852)Охрана труда-(3308)Педагогика-(5571)Полиграфия-(1312)Политика-(7869)Право-(5454)Приборостроение-(1369)Программирование-(2801)Производство-(97182)Промышленность-(8706)Психология-(18388)Религия-(3217)Связь-(10668)Сельское хозяйство-(299)Социология-(6455)Спорт-(42831)Строительство-(4793)Торговля-(5050)Транспорт-(2929)Туризм-(1568)Физика-(3942)Философия-(17015)Финансы-(26596)Химия-(22929)Экология-(12095)Экономика-(9961)Электроника-(8441)Электротехника-(4623)Энергетика-(12629)Юриспруденция-(1492)Ядерная техника-(1748)

Язык JAVA. Потоки




Язык JAVA. Апплеты. Включение апплетов на HTML страницу.

http://www.helloworld.ru/texts/comp/lang/java/java/15.htm

Апплеты — это маленькие приложения, которые размещаются на серверах Internet, транспортируются клиенту по сети, автоматически устанавливаются и запускаются на месте, как часть документа HTML. Когда апплет прибывает к клиенту, его доступ к ресурсам ограничен.

Ниже приведен исходный код канонической программы HelloWorld, оформленной в виде апплета:

import java.awt.*;
import java.applet.*;
public class HelloWorldApplet extends Applet {
public void paint(Graphics g) {
g.drawString("Hello World!", 20, 20);
} }

Для запуска этого апплета в браузере необходим следующий HTML-код:

<applet code="HelloWorldApplet" width=200 height=40>
</applet>

Вы можете поместить эти строки в отдельный html-файл (HelloWorldApplet.html), либо вставить их в текст этой программы в виде комментария и запустить программу appletviewer с его исходным текстом в качестве аргумента.

Тег HTML <Applet>

Тег <applet> используется для запуска апплета как из HTML-документа, так и из программы appletviewer. Программа appletviewer выполняет каждый найденный ей тег <applet> в отдельном окне, в то время как браузеры позволяют разместить на одной странице несколько апплетов. Синтаксис тэга <APPLET> в настоящее время таков:

<APPLET

CODE = appletFile
OBJECT = appletSerialFile
WIDTH = pixels
HEIGHT = pixels
[ARCHIVE = jarFiles]
[CODEBASE = codebaseURL]
[ALT = alternateText]
[NAME = appletInstanceName]
[ALIGN = alignment]
[VSPACE = pixels]
[HSPACE = pixels]
>
[< PARAM NAME = AttributeNamel VALUE = AttributeValuel >]
[< PARAM NAME = AttributeName2 VALUE = AttributeValue2 >]
[HTML-текст, отображаемый при отсутствии поддержки Java]
</APPLET>

Передача параметров: <applet code=Testing width=40 height=40> <param name=fontName value=Univers> <param name=fontSize value=14> <param name=leading value=2> <param name=accountEnabled value=true> Извлечение параметров: String FontName = getParameter("fontName"); String FontSize = Integer.parseInt(getParameter("fontSize")); String Leading = Float.valueOf(getParameter("leading")); String PaidUp = Boolean.valueOf(getParameter("accountEnabled"));

 


http://java.sun.com/javase/6/docs/api/java/lang/Thread.html

http://www.freejavaguide.com/java-threads-tutorial.pdf

class PrimeThread extends Thread { long minPrime; PrimeThread(long minPrime) { this.minPrime = minPrime; } public void run() { //compute primes larger than minPrime... }}   PrimeThread p = new PrimeThread(143);p.start(); class PrimeRun implements Runnable { long minPrime; PrimeRun(long minPrime) { this.minPrime = minPrime; } public void run() { //compute primes larger than minPrime... }}   PrimeRun p = new PrimeRun(143);new Thread(p).start();

The Java language provides two keywords for ensuring that data can be shared between threads in a controlled manner: synchronized and volatile.

Synchronized has two important meanings: it ensures that only one thread executes a protected section of code at one time (mutual exclusion or mutex), and it ensures that data changed by one thread is visible to other threads (visibility of changes).

Without synchronization, it is easy for data to be left in an inconsistent state. Synchronization allows to define blocks of code that must run atomically, in which they appear to execute in an all-or-nothing manner, as far as other threads can tell.

It is possible for two threads executing on two different processors to see two different values for the same variable! (if a memory location is modified in the cache on one processor, it is not necessarily visible to other processors until the writer's cache is flushed and the reader's cache is invalidated)

Volatile is simpler than synchronization and is suitable only for controlling access to single instances of primitive variables -- integers, booleans, and so on. When a variable is declared volatile, any write to that variable will go directly to main memory, bypassing the cache, while any read of that variable will come directly from main memory, bypassing the cache. This means that all threads see the same value for a volatile variable at all times.

 

The Object class defines the methods wait(), notify(), and notifyAll(). To execute any of these methods, you must be holding the lock for the associated object.

Wait() causes the calling thread to sleep until it is interrupted with Thread.interrupt(), the specified timeout elapses, or another thread wakes it up with notify() or notifyAll().

When notify() is invoked on an object, if there are any threads waiting on that object via wait(), then one thread will be awakened. When notifyAll() is invoked on an object, all threads waiting on that object will be awakened.

public class SyncExample { private static lockObject = new Object(); private static class Thread1 extends Thread { public void run() { synchronized (lockObject) { x = y = 0; System.out.println(x); } } } private static class Thread2 extends Thread { public void run() { synchronized (lockObject) { x = y = 1; System.out.println(y); } } } public static void main(String[] args) { new Thread1().run(); new Thread2().run(); } } The simplest way to create a synchronized block is to declare a method as synchronized. This means that before entering the method body, the caller must acquire a lock: public class Point { public synchronized void setXY(int x, int y) { this.x = x; this.y = y; } } For ordinary synchronized methods, this lock will be the object on which the method is being invoked. For static synchronized methods, this lock will be the monitor associated with the Class object in which the method is declared. Just because setXY() is declared as synchronized doesn't mean that two different threads can't still execute setXY() at the same time, as long as they are invoking setXY() on different Point instances. Only one thread can execute setXY(), or any other synchronized method of Point, on a single Point instance at one time.

 





Поделиться с друзьями:


Дата добавления: 2015-01-03; Просмотров: 411; Нарушение авторских прав?; Мы поможем в написании вашей работы!


Нам важно ваше мнение! Был ли полезен опубликованный материал? Да | Нет



studopedia.su - Студопедия (2013 - 2024) год. Все материалы представленные на сайте исключительно с целью ознакомления читателями и не преследуют коммерческих целей или нарушение авторских прав! Последнее добавление




Генерация страницы за: 0.009 сек.