盒子
盒子
文章目录
  1. Objective 4.1 Defining, Instantiating, and Starting Threads
    1. Defining a Thread
      1. Extend the java.lang.Thread class
      2. Implement the java.lang.Runnable interface
    2. Instantiating a Thread

Java Thread

Objective 4.1 Defining, Instantiating, and Starting Threads

Defining a Thread

Extend the java.lang.Thread class

  1. extend the java.lang.Thread class
  2. override the run() method
1
2
3
4
5
6
7
8
9
10
11
12
13
class MyThread extends Thread {

public void run() {
System.out.println("Running the task in a seperate thread");
}

// can overload the run() method, but it will be ignored by the Thread class
// unless you call it yourself, and it will be executed in the current call stack

public void run(String s) {
System.out.println("String in run is: " + s);
}
}

Implement the java.lang.Runnable interface

1
2
3
4
5
6
7
8
class MyRunnable implements Runnable {

public void run() {
System.out.println("Important job running in MyRunnable.");
}


}

Instantiating a Thread

Every thread of execution begins as an instance of class Thread.

1
2
3
4
5
6
7
8
9
10
MyThread t = new MyThread();

MyRunnable r = new MyRunnable();
Thread t = new Thread(r);

// Constructors need to know
Thread()
Thread(Runnable target)
Thread(Runnable target, String name)
Thread(String name)

new -> runnable alive -> dead

start()

yield()

sleep()

run()

getState() method
isAlive() start() is called but run() is not called

Thread & Locks. 考得不多但是面ebay碰到了. 主要知识点: thread和process区别, multithread, lock, semaphore, 对resource分配, deadlock, 怎么解决/预防deadlock. 还有BlockingQueue 和 Producer-Consumer经典题要会implement.
这里有几个经典问题:
https://www.careercup.com/question?id=4783236498587648
https://www.careercup.com/question?id=5652784707796992

  • Semaphore:

When a process encounters a semaphore, it performs a test to determine whether someone else is currently accessing the resources the semaphore protects.
If so, the process blocks and waits until another process signals that the resource is available. Since many process may be waiting on a resource, some
implementions of semaphores use a queue to determine who is next to go.

支持一下
扫一扫,支持forsigner
  • 微信扫一扫
  • 支付宝扫一扫