Multithreading - educoder practical training homework questions and answers

Table of contents

Java Advanced Features - Multithreading Basics (1) Using Threads

Level 1: Create a thread

Level 2: Create threads using Callable and Future

Java Advanced Features - Multithreading Basics (2) Common Functions

Level 1: Thread status and schedulingEdit

Level 2: Commonly used functions (1)

Level 3: Commonly used functions (2)

Java Advanced Features - Multi-Threading Basics (3) Thread Synchronization

Level 1: Three concepts of concurrent programmingEdit

 Level 2: Synchronize threads using the synchronized keyword

Level 3: Using thread lock (Lock) to achieve thread synchronization

Level 4: Using volatile to achieve variable visibility

Java Advanced Features-Multi-Threading Exercises

Level 1: Sequential output

Level 2: Ticket Window


Java Advanced Features - Multithreading Basics (1) Using Threads

Level 1: Create a thread

package step1;

//请在此添加实现代码
/********** Begin **********/
public class ThreadClassOne extends Thread    {
    public int i=0;
	public ThreadClassOne(){
		super();
	}
	public void run(){
		for(i=0;i<10;i++){
			if(i%2==1)
				System.out.print(i+" ");
		}
	}
}


/********** End **********/

Level 2: Create threads using Callable and Future

package step2;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
public class Task {
	public void runThread(int num) {
    //请在此添加实现代码
/********** Begin **********/
	// 在这里开启线程 获取线程执行的结果
	Callable callable = new ThreadCallable(num);
	FutureTask<Integer> futureTask = new FutureTask<>(callable);
	new Thread(futureTask).start();//开启线程
	try {
		Integer result = futureTask.get();
		System.out.println("线程的返回值为:" + result);
	} catch (Exception e) {
		e.printStackTrace();
	}
/********** End **********/
	}
}
//请在此添加实现代码
/********** Begin **********/
/* 在这里实现Callable接口及方法 */
class ThreadCallable implements Callable<Integer>{
	private int num;
    public ThreadCallable() {
    }
    public ThreadCallable(int num) {
        this.num = num;
    }
    public Integer call() throws Exception {
        int[] arr = new int[2];
        arr[0] = 1;
        arr[1] = 1;
        for (int i = 2; i < num; i++) {
            int tmp = arr[1];
            arr[1] = arr[0] + arr[1];
            arr[0] = tmp;
        }
        return arr[1];
    }
}
/********** End **********/

Java Advanced Features - Multithreading Basics (2) Common Functions

Level 1: Thread status and scheduling

 

Level 2: Commonly used functions (1)

package step2;

import java.util.Scanner;

public class Task {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int num = sc.nextInt();
		//请在此添加实现代码
     /********** Begin **********/
	 Thread t = new MyThread("子线程",num);
		t.start();

    /********** End **********/
		
		
	}
}


		//请在此添加实现代码
   /********** Begin **********/

class MyThread extends Thread{
	private int num;
	private String name;
	public MyThread(String name,int num){
		this.num=num;
		this.name=name;
	}
	public void run(){
		int[] arr = new int[2];
        arr[0] = 1;
        arr[1] = 1;
        for (int i = 2; i < num; i++) {
            int tmp = arr[1];
            arr[1] = arr[0] + arr[1];
            arr[0] = tmp;
        }
        System.out.println("子线程计算结果为:"+arr[1]);
	}
}

	


   /********** End **********/

Level 3: Commonly used functions (2)

package step3;
public class MyThread implements Runnable {   
//请在此添加实现代码
/********** Begin **********/
private String name;
	private Object prev;
	private Object self;
	private MyThread(String name,Object prev,Object self){
		this.name = name;
		this.prev = prev;
		this.self = self;
	}
	public void run(){
		int count = 5;
		while(count>0){
			synchronized(prev){
				synchronized(self){
					System.out.print(name);
					count--;
					self.notify();
				}
				try {
                    prev.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
				}
			}
		}
		System.exit(0);
	}
 	public static void main(String[] args) throws Exception {   
        Object a = new Object();
        Object b = new Object();
        Object c = new Object();
		MyThread ta = new MyThread("E",c,a);
		MyThread tb = new MyThread("D",a,b);
		MyThread tc = new MyThread("U",b,c);
		new Thread(ta).start();
		Thread.sleep(100);
		new Thread(tb).start();
		Thread.sleep(100);
		new Thread(tc).start();
		Thread.sleep(100);
    }   
/********** End **********/  
}

Java Advanced Features - Multi-Threading Basics (3) Thread Synchronization

Level 1: Three concepts of concurrent programming

 

 Level 2: Synchronize threads using the synchronized keyword

package step2;
public class Task {
	public static void main(String[] args) {
		final insertData insert = new insertData();
		for (int i = 0; i < 3; i++) {
			new Thread(new Runnable() {
				public void run() {
					insert.insert(Thread.currentThread());
				}
			}).start();
		}		
		
	}
}
class insertData{
	public static int num =0;
	/********* Begin *********/
	public synchronized void insert(Thread thread){
		for (int i = 0; i <= 5; i++) {
			num++;
			System.out.println(num);
		}
	}
	/********* End *********/
}

Level 3: Using thread lock (Lock) to achieve thread synchronization

package step3;
 
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
 
public class Task {
    public static void main(String[] args) throws InterruptedException {
        final Insert insert = new Insert();
        Thread t1 = new Thread(new Runnable() {
            public void run() {
                insert.insert(Thread.currentThread());
            }
        });
        Thread t2 = new Thread(new Runnable() {
            public void run() {
                insert.insert(Thread.currentThread());
            }
        });
        Thread t3 = new Thread(new Runnable() {
            public void run() {
                insert.insert(Thread.currentThread());
            }
        });
        // 设置线程优先级
        /*
        t1.setPriority(Thread.MAX_PRIORITY);
        t2.setPriority(Thread.NORM_PRIORITY);
        t3.setPriority(Thread.MIN_PRIORITY);
        t1.start();
        t2.start();
        t3.start();
        */
        t1.start();
        t2.sleep(500);
        t2.start();
        t3.sleep(1000);
        t3.start();
    }
}
 
class Insert {
    public static int num;
    // 在这里定义Lock
    private Lock lock = new ReentrantLock();
 
    public void insert(Thread thread) {
        /********* Begin *********/
        if (lock.tryLock()) {
            try {
                System.out.println(thread.getName() + "得到了锁");
                for (int i = 0; i < 5; i++) {
                    num++;
                    System.out.println(num);
                }
            } finally {
                System.out.println(thread.getName() + "释放了锁");
                lock.unlock();
            }
        } else {
            System.out.println(thread.getName() + "获取锁失败");
        }
    }
    /********* End *********/
}
 

Level 4: Using volatile to achieve variable visibility

package step4;
 
public class Task {
	public volatile int inc = 0;
	//请在此添加实现代码
	/********** Begin **********/
	public synchronized void increase() {
		inc++;
	}
	/********** End **********/
	public static void main(String[] args) {
		final Task test = new Task();
		for (int i = 0; i < 10; i++) {
			new Thread() {
				public void run() {
					for (int j = 0; j < 1000; j++)
						test.increase();
				};
			}.start();
		}
		while (Thread.activeCount() > 1) // 保证前面的线程都执行完
			Thread.yield();
		System.out.println(test.inc);
	}
}
 

Java Advanced Features-Multi-Threading Exercises

Level 1: Sequential output

package step1;
public class Task {
	public static void main(String[] args) throws Exception {
		/********* Begin *********/
		//在这里创建线程, 开启线程
	 Object a = new Object();
        Object b = new Object();
        Object c = new Object();
		MyThread ta = new MyThread("A",c,a);
		MyThread tb = new MyThread("B",a,b);
		MyThread tc = new MyThread("C",b,c);
		ta.start();
		ta.sleep(100);
		tb.start();
		tb.sleep(100);
		tc.start();
		tc.sleep(100);	
		/********* End *********/
	}
}
class MyThread extends Thread {
	/********* Begin *********/
	private String threadName;
	private Object prev;
	private Object self;
	public MyThread(String name,Object prev,Object self){
		this.threadName = name;
		this.prev = prev;
		this.self = self;
	}
	public void run() {
		int count = 5;
		while(count>0){
			synchronized(prev){
				synchronized(self){
					System.out.println("Java Thread"+this.threadName+this.threadName);
					count--;
					self.notify();
				}
				try {
                    prev.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
				}
			}
		}
		System.exit(0);
	}
	/********* End *********/
}

Level 2: Ticket Window

package step2;
/********* Begin *********/
//定义站台类,实现卖票的功能。
public class Station extends Thread{	 
	static int tick = 20; // 为了保持票数的一致,票数要静态
    static Object ob = new Object(); // 创建一个静态钥匙 值是任意的
    public void ticket() {
        System.out.println( "卖出了第" + tick + "张票");
        tick--;
    }
    public void run() {
        while (tick > 0) {
            synchronized (ob) {
                if (tick > 0) {
                    ticket();
                } 
            }
            if(tick == 0){
                System.out.println("票卖完了");
            }
            try {
                Thread.sleep(100);
            } catch (Exception e) {
            }
        }
	}
}



/********* End *********/

Guess you like

Origin blog.csdn.net/qq_35353972/article/details/126967432