public class Archiver {
public static long count = 0 ;
class Task {
// ...
void work ( String taskId ) {
count + = something ( taskId ) ;
count + = somethingElse ( taskId ) ;
count + = commit ( taskId ) ;
}
}
public static void main ( String [ ] args ) {
for ( String id : args )
new Task ( ) . work ( id ) ;
System . out . println ( Task. count ) ;
}
}
public class Archiver {
public static long count = 0 ;
class Task implements Runnable {
// ...
public void run ( ) {
timeout = 0 ;
while ( timeout < 10 ) {
if ( haveMoreTasks ( ) ) {
taskId = getTask ( ) ;
count + = something ( taskId ) ;
count + = somethingElse ( taskId ) ;
count + = commit ( taskId ) ;
} else {
Thread . sleep ( 10 ) ;
timeout ++;
}
}
}
}
private static LinkedList < String > tasks ;
synchronized public static String getTask ( ) {
return tasks. pollLast ( ) ;
}
synchronized public static boolean haveMoreTasks ( ) {
return tasks. size ( ) > 0 ;
}
publicized static static void addTask ( String taskId ) {
tasks. add ( task ) ;
}
public static void main ( String [ ] args ) {
for ( String id : args )
addTask ( id ) ;
int threadNum = Runtime . getRuntime ( ) . availableProcessors ( ) ;
for ( int i = 0 ; i < threadNum ; i ++ )
( threads [ i ] = new thread ( new Task ( ) ) ) . start ( ) ;
boolean finished = false ;
while ( ! finished ) {
finished = true ;
for ( int i = 0 ; i < threadNum ; i ++ )
finished & = ! threads [ i ] . isAlive ( ) ;
try {
Thread . sleep ( 10 ) ;
} catch ( Exception e ) {
e. printStackTrace ( ) ;
}
}
System . out . println ( count ) ;
}
}
long delta = something ( taskId ) ;The calculation of the result from the synchronized block follows because it can be performed for a very long time, thereby blocking the work of other threads;
delta + = somethingElse ( taskId ) ;
delta + = commit ( taskId ) ;
synchronized ( count ) {
count. + = delta ;
}
public class Archiver implements Runnable {
public static AtomicLong count = AtomicLong (0 ) ;
public static String [ ] tasks ;
class Task implements Runnable {
Task ( String taskId ) {
this . taskId = taskId ;
}
// ...
public void run ( ) {
long delta = something ( taskId ) ;
delta + = somethingElse ( taskId ) ;
delta + = commit ( taskId ) ;
synchronized ( count ) {
count. addAndGet ( delta ) ;
}
}
}
public void run ( ) {
int processors = runtime . getRuntime ( ) . availableProcessors ( ) ;
ExecutorService pool = Executors. newFixedThreadPool ( processors ) ;
for ( String id : tasks )
pool. execute ( new Task ( id ) ) ;
pool. shutdown ( ) ;
try {
if ( ! pool. awaitTermination ( 20 , TimeUnit. MINUTES ) )
throw new InterruptedException ( "Time Limit Exceeded" ) ;
} catch ( InterruptedException e ) {
e. printStackTrace ( ) ;
pool. shutdownNow ( ) ;
System . exit ( 1 ) ;
}
System . out . println ( count ) ;
}
public static void main ( String [ ] args ) {
tasks = args ;
new thread ( new archiver ( ) ) . start ( ) ;
}
}
Source: https://habr.com/ru/post/73249/