Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package spo.labs.lab1;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Scanner;
- import java.util.Set;
- public class ThreadMain {
- private static int index = 0;
- public static void main(String[] args) throws InterruptedException {
- Scanner reader = new Scanner(System.in);
- char c = reader.next().trim().charAt(0);
- List<Thread> threadList = new ArrayList<>();
- CommonResource commonResource = new CommonResource();
- while (c != 'q') {
- switch (c) {
- case '+':
- System.out.println("New Thread");
- // thread.start();
- new Thread(new ChildThreads(commonResource)).setName("Thread " + ++index);
- Thread.currentThread().start();
- threadList.add(Thread.currentThread());
- break;
- case '-':
- if (!threadList.isEmpty()){
- System.out.println("Kill Thread");
- }
- break;
- case 'a':
- System.out.println("All threads:\n");
- Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
- for (Thread t : threadSet){
- System.out.println("Thread " + t + " state: " + t.getState());
- }
- System.out.println("-----------------------------");
- for (Thread thread1 : threadList){
- System.out.println(thread1.getName() + " State:" + thread1.getState());
- }
- }
- c = reader.next().trim().charAt(0);
- }
- }
- }
- package spo.labs.lab1;
- public class CommonResource {
- synchronized void showString() {
- System.out.printf("%s \n", Thread.currentThread().getName());
- // try {
- // Thread.sleep(100);
- // } catch (InterruptedException e) {
- // e.printStackTrace();
- // }
- }
- }
- package spo.labs.lab1;
- public class ChildThreads implements Runnable {
- CommonResource resource;
- public ChildThreads(CommonResource resource) {
- this.resource = resource;
- }
- @Override
- public void run() {
- resource.showString();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement