Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 1.
- public class TwoThreads {
- public static class ThreadAB implements Runnable {
- public String s1,s2;
- public ThreadAB(String s1, String s2) {
- this.s1 = s1;
- this.s2 = s2;
- }
- public void run() {
- System.out.println(s1);
- System.out.println(s2);
- }
- }
- public static void main(String[] args) {
- Runnable t = new ThreadAB("A","B");
- Thread tnew = new Thread(t);
- Runnable t2 = new ThreadAB("1","2");
- Thread tnew2 = new Thread(t2);
- tnew.start();
- tnew2.start();
- }
- }
- 2.
- import java.util.HashSet;
- import java.util.Random;
- import java.util.Scanner;
- import java.util.concurrent.Semaphore;
- public class CountThree {
- public static int NUM_RUNS = 100;
- /**
- * Promenlivata koja treba da go sodrzi brojot na pojavuvanja na elementot 3
- */
- int count = 0;
- /**
- * TODO: definirajte gi potrebnite elementi za sinhronizacija
- */
- public Semaphore semaphore;
- public void init() {
- semaphore=new Semaphore(1);
- }
- class Counter extends Thread {
- public void count(int[] data) throws InterruptedException {
- // da se implementira
- semaphore.acquire();
- for (int i=0; i<data.length; i++) {
- if (data[i]==3) {
- count++;
- }
- }
- semaphore.release();
- }
- private int[] data;
- public Counter(int[] data) {
- this.data = data;
- }
- @Override
- public void run() {
- try {
- count(data);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- public static void main(String[] args) {
- try {
- CountThree environment = new CountThree();
- environment.start();
- } catch (Exception ex) {
- ex.printStackTrace();
- }
- }
- public void start() throws Exception {
- init();
- HashSet<Thread> threads = new HashSet<Thread>();
- Scanner s = new Scanner(System.in);
- int total=s.nextInt();
- Random r=new Random();
- for (int i = 0; i < NUM_RUNS; i++) {
- int[] data = new int[total];
- for (int j = 0; j < total; j++) {
- data[j] = s.nextInt();
- // data[j]=r.nextInt(20);
- }
- Counter c = new Counter(data);
- threads.add(c);
- }
- for (Thread t : threads) {
- t.start();
- }
- for (Thread t : threads) {
- t.join();
- }
- System.out.println(count);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement