![]() |
|
Модераторы: LSD, AntonSaburov |
![]()
|
|
| Gost' |
|
|||
|
Unregistered |
Privet, ALL!
public class Server extends Thread { int i=0; ............... public static void main (String[] args) throws IOException { try { ServerSocket Server = new ServerSocket(port); while(true) { Server Ser = new Server(Server.accept()); Ser.start(); } } catch(Exception e) {System.out.println("init error: "+e);} } ............... public Server (Socket NewClient) { this.NewClient = NewClient; } public void run () { //zdes nado izmeniat peremennuju i, tak chtoby ona izmenilas dlia vseh novyh threadov } Zaranee blagodaren za liubuju pomosh. |
|||
|
||||
| sergejzr |
|
||||
![]() Un salsero Профиль Группа: Админ Сообщений: 13285 Регистрация: 10.2.2004 Где: Германия г .Ганновер Репутация: 6 Всего: 360 |
Попробуй вместо:
вот это:
А вообще лучше определи функции set и get вот ссылка: http://forum.vingrad.ru/index.php?showtopic=21752 PS: пожалуйста, пользуйся www.translit.ru Это сообщение отредактировал(а) sergej.z - 10.5.2004, 19:13 |
||||
|
|||||
| Gost' |
|
|||
|
Unregistered |
Спасибо за помощь, Сергей.
|
|||
|
||||
| Domestic Cat |
|
|||
![]() Эксперт ![]() ![]() ![]() ![]() Профиль Группа: Экс. модератор Сообщений: 5452 Регистрация: 3.5.2004 Где: Dallas, US Репутация: 50 Всего: 172 |
Anyway you should remember that this (class) variable will not be thread-safe
(and instance variables as well). Therefore you should think about synchronization - sure, if is not just simple counter or something. -------------------- |
|||
|
||||
| LSD |
|
|||
![]() Leprechaun Software Developer ![]() ![]() ![]() ![]() Профиль Группа: Модератор Сообщений: 15718 Регистрация: 24.3.2004 Где: Dublin Репутация: 210 Всего: 538 |
2 Domestic Cat
Самим по себе примитивным типам синхронизация не нужна. Она нужна если у него есть другие поля которые нужно менять синхронно с i (например массив содержащий ссылки на экземпляры класса). Тогда действительно синхронизация нужна. А если i это только счетчик, то его можно и не синхронизировать. -------------------- Disclaimer: this post contains explicit depictions of personal opinion. So, if it sounds sarcastic, don't take it seriously. If it sounds dangerous, do not try this at home or at all. And if it offends you, just don't read it. |
|||
|
||||
| Domestic Cat |
|
||||
![]() Эксперт ![]() ![]() ![]() ![]() Профиль Группа: Экс. модератор Сообщений: 5452 Регистрация: 3.5.2004 Где: Dallas, US Репутация: 50 Всего: 172 |
Ooops. Sorry? I dont talk about primitives, I talk about synchronization in general (on class, method or block). Anything which is to be accessed by multiple threads, excluding LOCAL variables and REQUEST parameters (J2EE) must be accessed via synchronized methods or blocks unless you are completely sure that there will be NO side-effects. There are NO atomic operations in Java. Consider situation: thread A invokes method saveVariable() which just writes static field i: 1. A tries to write variable i. 2. While it is writing it, it is in UNSTABLE state. 3. Thread B invokes the same method and tries to read i, but it is in unstable state. This situation is quite exotic, however suppose that thread tries to do something with i. Say, thread A invokes method myMethod which does the following: 1. reads i 2. does some calculations 3. writes i. If thread B invokes the same method (and it is not synchronized, i.e. not thread-safe) it is impossible to know what time slicing will be done by scheduler, and you dont know what will happen. Thread B may perform step 1 when thread A ALREADY saved i, or just BEFORE that. Therefore you dont know what will be the result of method invocation. Surely if i is just a thread counter and every thread just increments it by unity, no synchronization is needed. But look here:
Probably, threads are supposed to do something with i - it is not clear. Say, thread 12 changes i, and thread 13 must have known that but it has already read i BEFORE 12 changed it. It would be error. This leads to that you need to access i through mutator method which is synchronized on something (any object, say arbitrary wrapper declared in this class). All other threads will wait till current thread will release the lock on this object and thus i will be thread-safe variable. Usually it is better to synchronize block of code rather than method or class. Anyways, it depends on authors implementation and what actually he does with i. -------------------- |
||||
|
|||||
| Gost |
|
|||
|
Unregistered |
In this case I only need to increase i in the begining of the thread and decrease it in the end of the same thread. So I doubt having any problems with accessing this i from different threads. The role of i is a number of clients connected at the moment.
|
|||
|
||||
| Domestic Cat |
|
|||
![]() Эксперт ![]() ![]() ![]() ![]() Профиль Группа: Экс. модератор Сообщений: 5452 Регистрация: 3.5.2004 Где: Dallas, US Репутация: 50 Всего: 172 |
Then much elegant solution would be to use ThreadGroup (activeCount()) rather than to save this number in static variable.
-------------------- |
|||
|
||||
| ElectricalStorm |
|
|||
![]() Опытный ![]() ![]() Профиль Группа: Участник Клуба Сообщений: 547 Регистрация: 22.1.2004 Репутация: 5 Всего: 9 |
сори за офф
Вот ё куда я попал .... а по русски можно ? -------------------- Нужно знать инструмент, которым пользуешься |
|||
|
||||
| Domestic Cat |
|
|||
![]() Эксперт ![]() ![]() ![]() ![]() Профиль Группа: Экс. модератор Сообщений: 5452 Регистрация: 3.5.2004 Где: Dallas, US Репутация: 50 Всего: 172 |
Sorry za English, but i have no russificator, no keyboard with russian letters and its takes a lot of time to use translit.ru ;->
Это сообщение отредактировал(а) Domestic Cat - 11.5.2004, 20:14 -------------------- |
|||
|
||||
| ElectricalStorm |
|
|||
![]() Опытный ![]() ![]() Профиль Группа: Участник Клуба Сообщений: 547 Регистрация: 22.1.2004 Репутация: 5 Всего: 9 |
tak pishite translitom
-------------------- Нужно знать инструмент, которым пользуешься |
|||
|
||||
| Gost' |
|
|||
|
Unregistered |
Возможно и удобнее, просто я новичок в JAVA, о таких вещах ещё не слышал. Но переменная static меня вполне устраивает на данном этапе.
|
|||
|
||||
| sergejzr |
|
||||||
![]() Un salsero Профиль Группа: Админ Сообщений: 13285 Регистрация: 10.2.2004 Где: Германия г .Ганновер Репутация: 6 Всего: 360 |
Мои советы тебе, как новичку:
__________________________________________________________ PS:
И нажимайте на ссылку Translit -> Russian! 2Gost' Спасибо за то, что воспользовался translit.ru, и мои глаза отдыхают читая твои посты. Это сообщение отредактировал(а) sergej.z - 12.5.2004, 01:26 |
||||||
|
|||||||
| Domestic Cat |
|
|||
![]() Эксперт ![]() ![]() ![]() ![]() Профиль Группа: Экс. модератор Сообщений: 5452 Регистрация: 3.5.2004 Где: Dallas, US Репутация: 50 Всего: 172 |
Vse-taki interesno, a na kakom yazike vy chitaete dokumentatsiyu, specifikacii etc ?
Programmist ne znayushii angliiskogo? Nu eto ya tak, iz merzkosti haraktera -------------------- |
|||
|
||||
| sergejzr |
|
|||
![]() Un salsero Профиль Группа: Админ Сообщений: 13285 Регистрация: 10.2.2004 Где: Германия г .Ганновер Репутация: 6 Всего: 360 |
Если мы так и будем продолжать - наши внуки ещё будут читать доку "по-американски"
/OFFTOP Не разу не читал документации на транслите. Я живу в Германии учусь на английском курсе, но не теряю надежды не разучить Великий и Могучий. /OFFTOP |
|||
|
||||
![]()
|
| Правила форума "Java" | |
|
|
Если Вам помогли, и атмосфера форума Вам понравилась, то заходите к нам чаще! С уважением, LSD, AntonSaburov, powerOn, tux, javastic. |
| 0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей) | |
| 0 Пользователей: | |
| « Предыдущая тема | Java: Общие вопросы | Следующая тема » |
|
|
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности Powered by Invision Power Board(R) 1.3 © 2003 IPS, Inc. |